python文件读写操作基础练习题
时间: 2024-04-12 14:22:31 浏览: 172
以下是Python文件读写操作基础练习题的答案:
1. 读取文件内容并打印
```python
with open('file.txt', 'r') as f:
content = f.read()
print(content)
```
2. 逐行读取文件内容并打印
```python
with open('file.txt', 'r') as f:
for line in f:
print(line.strip())
```
3. 写入文件
```python
with open('file.txt', 'w') as f:
f.write('Hello, world!')
```
4. 追加内容到文件
```python
with open('file.txt', 'a') as f:
f.write('\nHello again!')
```
5. 读取CSV文件并打印每行内容
```python
import csv
with open('file.csv', mode='r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
6. 以字典格式读取CSV文件并打印每个人的名字和电子邮件地址
```python
import csv
with open('user.csv', mode='r', encoding='utf-8') as f:
users = csv.DictReader(f)
for user in users:
print(user['name'], user['email'])
```
阅读全文