有没有办法让我阅读使用python保存在文本文件中的文件?
例如,我有一个名为filenames.txt
的文件。该文件的内容应具有其他文件的名称,例如:
/home/ikhwan/acespc.c
/home/ikhwan/trloc.cpp
/home/ikhwan/Makefile.sh
/home/ikhwan/Readme.txt
因此,理论上我想要做的是我有一个Python脚本来更改文件的某些标题。因此,只要我想运行脚本来更改所选文件,filenames.txt
就会充当我的平台。原因是我在目录和子目录中有这么多文件,我只想让python只读取我放在filenames.txt
内的文件,只改变那个特定的文件。将来,如果我想在其他文件上运行脚本,我只需在filenames.txt
所以脚本的流程如下:
运行脚本 - >脚本开始搜索filenames.txt中的文件名 - >脚本将添加或更改文件的标题。
当前,我使用os.walk但它将在所有目录和子目录中搜索。这是我目前的功能。
def read_file(file):
skip = 0
headStart = None
headEnd = None
yearsLine = None
haveLicense = False
extension = os.path.splitext(file)[1]
logging.debug("File extension is %s",extension)
type = ext2type.get(extension)
logging.debug("Type for this file is %s",type)
if not type:
return None
settings = typeSettings.get(type)
with open(file,'r') as f:
lines = f.readlines()
答案 0 :(得分:0)
如果您已经在filenames.txt
中列出了文件路径,只需打开它,逐行读取它,然后处理它的每个文件路径,您就不需要遍历文件系统了,例如
# this is your method that will be called with each file path from the filenames.txt
def process_file(path):
# do whatever you want with `path` in terms of processing
# let's just print it to STDOUT as an example
with open(path, "r") as f:
print(f.read())
with open("filenames.txt", "r") as f: # open filenames.txt for reading
for line in f: # read filenames.txt line by line
process_file(line.rstrip()) # send the path stored on the line to process_file()