2017-07-20 52 views
0

有没有什么方法可以读取我使用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

欢迎来到StackOverflow。请阅读并遵守帮助文档中的发布准则。 [在主题](http://stackoverflow.com/help/on-topic)和[如何提问](http://stackoverflow.com/help/how-to-ask)适用于此处。 StackOverflow不是一个设计,编码,研究或教程服务。 – Prune

+0

你给我们一个编程问题,没有明显的你自己的尝试。看来你还没有学会如何打开和读取文件。这表明你需要一些时间与当地的导师或一个教程的步行,而不是堆栈溢出。 – Prune

+0

目前我使用递归函数,以便它将读取目录和子目录中的所有文件。这里是我目前的代码。 – Ikhwan

回答

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() 
+0

这是否仍然适用,如果我改变或添加文件内的另一个路径? – Ikhwan

+0

@Ikhwan - 你可以在你的''filenames.txt'文件中添加/修改/删除文件路径 - 每当你运行上面的脚本时,将为每个路径调用'process_file()'函数。 – zwer

+0

如何打开文件之一?例如,我想打印acespc.c的所有内容 – Ikhwan