示例示例Python读写文件的方式有很多种,介绍其中两种:使用open()函数来读写文件
Python读写文件的方式有很多种,介绍其中两种:
1. 使用open()函数来读写文件
要使用open()函数来读写文件,需要指定文件名和操作模式,操作模式有:
- 'r':只读模式,默认模式,如果文件不存在则抛出异常
- 'w':只写模式,如果文件不存在则创建新文件,如果文件存在则覆盖原文件
- 'a':追加模式,如果文件不存在则创建新文件,如果文件存在则在文件末尾追加内容
代码示例:
# 读文件
f = open('test.txt', 'r')
content = f.read()
f.close()
print(content)
# 写文件
f = open('test.txt', 'w')
f.write('This is a test file.')
f.close()
2. 使用with语句来读写文件
使用with语句可以自动调用close()函数,无需手动调用close()函数。
代码示例:
# 读文件
with open('test.txt', 'r') as f:
content = f.read()
print(content)
# 写文件
with open('test.txt', 'w') as f:
f.write('This is a test file.')
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(35条)