python文件读写
时间: 2023-08-01 18:08:30 浏览: 107
Python提供了多种处理文件的方法。下面是一些常见的文件读写操作示例:
1. 文件读取:
```python
# 打开文件
file = open('file.txt', 'r') # 可以使用相对或绝对路径
# 读取整个文件内容
content = file.read()
print(content)
# 逐行读取文件内容
for line in file:
print(line)
# 关闭文件
file.close()
```
2. 文件写入:
```python
# 打开文件(如果文件不存在则创建)
file = open('file.txt', 'w') # 可以使用相对或绝对路径
# 写入内容
file.write('Hello, World!\n')
file.write('This is a test.')
# 关闭文件
file.close()
```
请注意,在使用完文件后,要确保及时关闭文件,以释放资源。
另外,还有一种更简洁的方式是使用 `with` 语句,它会自动管理文件的打开和关闭,推荐使用这种方式:
```python
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('file.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is a test.')
```
希望对你有所帮助!如果你有其他问题,请随时提问。
阅读全文
相关推荐













