python对各种文件的读写
时间: 2023-08-20 13:04:06 浏览: 90
Python读写文件
Python供了许多内置函数和模块来读写各种类型的文件。下面是一些示例:
1. 打开文本文件并读取内容:
```python
with open('file.txt', 'r') as f:
content = f.read()
```
2. 写入文本文件:
```python
with open('file.txt', 'w') as f:
f.write('Hello, world!')
```
3. 打开二进制文件并读取内容:
```python
with open('file.bin', 'rb') as f:
content = f.read()
```
4. 写入二进制文件:
```python
with open('file.bin', 'wb') as f:
f.write(b'\x01\x02\x03')
```
5. 使用csv模块读写CSV文件:
```python
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
with open('file.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', 25])
writer.writerow(['Bob', 30])
```
6. 使用json模块读写JSON文件:
```python
import json
with open('file.json', 'r') as f:
data = json.load(f)
with open('file.json', 'w') as f:
json.dump(data, f)
```
这些只是Python读写文件的一些基本功能,还有其他更高级的技术可以帮助您处理各种文件格式。
阅读全文