python 用 with 打开文档没有如何自己创建
python 用 with 打开文档没有如何自己创建
python 用 with 打开文档没有如何自己创建
python 用 with 打开文档没有如何自己创建
当你说“用with打开文档没有如何自己创建”时,我假设你是在问如何在Python中使用with
语句来打开一个文件,并创建一个新的文件。
首先,让我们先来看一下如何使用with
语句来打开一个文件:
with open('filename.txt', 'r') as file:
content = file.read()
print(content)
在上面的代码中,open('filename.txt', 'r')
会打开名为filename.txt
的文件进行读取。第二个参数'r'
表示我们打开文件以读取内容。with
语句用于处理文件的打开和关闭,这样就不需要手动关闭文件。在with
语句的代码块结束时,文件会自动关闭。
如果你想自己创建一个新的文件并写入内容,你可以使用'w'
模式:
with open('newfile.txt', 'w') as file:
file.write('Hello, world!')
上面的代码会创建一个名为newfile.txt
的新文件,并写入字符串Hello, world!
。
如果你想在文件中添加内容而不是覆盖原有内容,你可以使用'a'
模式:
with open('newfile.txt', 'a') as file:
file.write('\nHello again, world!')
上面的代码会在文件的末尾添加字符串Hello again, world!
。注意,我们在字符串前面加了一个换行符(\n
),这是为了确保新的内容从新的一行开始。
os.path.exists()方法判断文件是否存在,如果不存在则创建文件
import os
if os.path.exists('test.txt'):
with open('test.txt',mode='r',encoding='utf-8') as ff:
print(ff.readlines())
else:
with open("test.txt", mode='w', encoding='utf-8') as ff:
print("文件创建成功!")
https://blog.csdn.net/Fantasy_Virgo/article/details/82315727
https://wenku.csdn.net/answer/cf6493ef1712432e8908e50866f211d8
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
不存在的可能性有两种,一种是文件不存在,一种是目录不存在,都需要处理。