Python文件操作习题
时间: 2023-12-14 12:34:43 浏览: 98
Python100经典练习题_python_经典练习题_
以下是Python文件操作的练习题及其解答:
练习一:写一个程序在要保持文件内容的顺序不变的前提下,去除文件中重复的行。
```python
import os
with open('db.txt', 'r', encoding='utf-8') as read_f, \
open('db.txt.swap', 'w', encoding='utf-8') as write_f:
s = set()
for line in read_f:
if line not in s:
s.add(line)
write_f.write(line)
os.remove('db.txt')
os.rename('db.txt.swap', 'db.txt')
```
练习二:写一个程序,将一个文件中的所有数字加总。
```python
with open('numbers.txt', 'r') as f:
total = 0
for line in f:
try:
num = int(line.strip())
total += num
except ValueError:
pass
print(total)
```
练习三:写一个程序,将一个文件中的所有单词按字母顺序排序后输出。
```python
with open('words.txt', 'r') as f:
words = []
for line in f:
words.extend(line.strip().split())
words.sort()
print(words)
```
阅读全文