使用Python进行文件读写实例
在Python中,我们可以使用内置的open()
函数来读写文件。以下是一些基本的例子:
- 打开文件读取:
# 打开文件以读模式
file = open('example.txt', 'r')
# 读取整个文件
content = file.read()
print(content) # 输出文件内容
# 关闭文件
file.close()
- 创建并写入文件:
# 创建新文件并写入内容
with open('new_example.txt', 'w') as file:
file.write('This is the content of the new file.\n')
print('File content written successfully!\n')
这样,你就可以根据需要使用Python进行文件读写了。
还没有评论,来说两句吧...