【问题标题】:How to open and read text files in a folder python如何打开和读取文件夹python中的文本文件
【发布时间】:2020-03-29 12:04:39
【问题描述】:

我有一个文件夹,里面有一个文本文件。我希望能够输入该文件的路径并让 python 遍历该文件夹,打开每个文件并将其内容附加到列表中。

import os

folderpath = "/Users/myname/Downloads/files/"
inputlst = [os.listdir(folderpath)]
filenamelist = []

for filename in os.listdir(folderpath):
    if filename.endswith(".txt"):
        filenamelist.append(filename)

print(filename list)

到目前为止,这个输出:

['test1.txt', 'test2.txt', 'test3.txt', 'test4.txt', 'test5.txt', 'test6.txt', 'test7.txt', 'test8.txt', 'test9.txt', 'test10.txt']

我想让代码获取这些文件中的每一个,打开它们并将其所有内容放入一个巨大的列表中,而不仅仅是打印文件名。有没有办法做到这一点?

【问题讨论】:

  • 欢迎来到 SO!文件中的内容是什么样的,结果列表应该如何显示(显示小的、有代表性的、可重现的 sn-ps)? inputlst = [os.listdir(folderpath)] 在您的代码中未使用,并且可能不会执行您想要的操作(inputlst = os.listdir(folderpath) 会更有意义)。

标签: python list directory


【解决方案1】:

如果你使用的是 Python3,你可以使用:

for filename in filename_list :
    with open(filename,"r") as file_handler :
        data = file_handler.read()

请注意,您需要filename中文件的完整(相对或绝对)路径

这样,当您离开with 范围时,您的文件处理程序将自动关闭。 更多信息在这里:https://docs.python.org/fr/3/library/functions.html#open

附带说明,为了列出文件,您可能需要查看glob 并使用:

filename_list = glob.glob("/path/to/files/*.txt")

【讨论】:

    【解决方案2】:

    您应该为此使用文件 open。 在此处阅读有关其advanced options的文档

    无论如何,这是一种方法:

    import os
    
    folderpath = r"yourfolderpath"
    inputlst = [os.listdir(folderpath)]
    filenamecontent = []
    
    for filename in os.listdir(folderpath):
        if filename.endswith(".txt"):
            f = open(os.path.join(folderpath,filename), 'r')
            filenamecontent.append(f.read())
    
    print(filenamecontent)
    

    【讨论】:

      【解决方案3】:

      你可以使用fileinput

      代码:

      
      import fileinput
      
      folderpath = "your_path_to_directory_where_files_are_stored"
      file_list = [a for a in os.listdir(folderpath) if a.endswith(".txt")]
      # This will return all the files which are in .txt format
      
      get_all_files = fileinput.input(file_list)
      
      with open("alldata.txt", 'ab+') as writefile:
          for line in get_all_files:
              writefile.write(line+'\n')
      
      

      上面的代码将从指定目录(文件夹路径)读取来自.txt的所有数据并将其存储在alldata.txt所以,你想要那个长列表,如果需要,该列表现在存储在 .txt 文件中,否则您可以删除写入过程。

      链接:

      https://docs.python.org/3/library/fileinput.html

      https://docs.python.org/3/library/functions.html#open

      【讨论】:

      • 您可能应该使用glob 而不是a.endswith(".txt"),因为它更灵活实用(您可以将路径指定为标准的unix路径模式,并且将返回所有匹配的文件路径)跨度>
      猜你喜欢
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      相关资源
      最近更新 更多