编写一个程序,其功能要求如下: 能够一屏一屏简单浏览指定文本文件; 将两个文本文件合并成一个文本文件; 给一个文本文件每一行加上行号存储到另一个文本文件中; 将一个文件中的所有小写字母转换成大写字母后存储到另一个文本文件中;
时间: 2024-01-21 12:19:25 浏览: 68
以下是 Python 的实现代码:
一屏一屏简单浏览指定文本文件:
```
def view_file(filename):
with open(filename, 'r') as f:
while True:
lines = f.readlines(10) # 每次读取 10 行
if not lines:
break
for line in lines:
print(line.strip()) # 输出去除换行符的每一行内容
input("按 Enter 继续...")
```
将两个文本文件合并成一个文本文件:
```
def merge_files(file1, file2, merge_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(merge_file, 'w') as mf:
mf.write(f1.read())
mf.write(f2.read())
```
给一个文本文件每一行加上行号存储到另一个文本文件中:
```
def add_line_numbers(source_file, target_file):
with open(source_file, 'r') as sf, open(target_file, 'w') as tf:
line_num = 1
for line in sf:
tf.write(f"{line_num:3d}: {line}")
line_num += 1
```
将一个文件中的所有小写字母转换成大写字母后存储到另一个文本文件中:
```
def upper_case(source_file, target_file):
with open(source_file, 'r') as sf, open(target_file, 'w') as tf:
for line in sf:
tf.write(line.upper())
```
以上代码可以根据需要进行调用。
阅读全文