问题描述
这里的python新手只是试图使某些过程自动化。经过一些研究,我了解到fileinput可用于在python中打开,读取和写入文件。为了解决我的问题,我认为我需要:
- 打开文件
- 创建文件备份
- 读取文件
- 为文件中的行数创建一个for循环
- 执行新行的创建
- 转到下一行并重复
- 保存并关闭文件
我无法从docs.python的文档中找出执行此操作所需的方法/功能,坦率地说,在阅读了其他一些文章后,我更加困惑,因为他们建议也使用其他模块。
任何帮助都将不胜感激,谢谢
解决方法
这是一个示例程序,
- 备份现有文件,
- 读取现有文件的行,
- 将修改后的行保存到新文件中,并且
- 跟踪行数。
此示例旨在展示Python的一些核心功能。例如,它显示了如何使用循环,如何打开文件以及如何在Python中使用字符串。
假设您有一个名为 somefile.txt 的文件:
This is a file. Hi to you!
并假设您在同一目录中有一个名为 example.py 的文件,其中包含以下几行:
import shutil # file copy
import os # new line separator
# the full path of the file
path = "somefile.txt"
# path to where to back it up
backup_path = "somefile.txt.bak"
# path to save output file
output_path = "output.txt"
# create backup first
shutil.copyfile(path,backup_path)
lineNumber = 0
# open the file for reading
with open(path) as input:
# open output for writing
with open(output_path,"w") as output:
# keep reading lines
while True:
# read a line from input
line = input.readline()
# end of file?
if line == "":
# break out of `while` loop
break
lineNumber += 1
# do something with the line
line = str(lineNumber) + ": " + line
# save to output
output.writelines(line)
# files are automatically closed for you
如果在包含example.py的目录中打开命令行并执行它,则应该看到两个新文件:
- somefile.txt.bak-somefile.txt的备份
- output.txt-somefile.txt的修改版本