[英]How to open and read text files in a folder python
我有一個文件夾,里面有一個文本文件。 我希望能夠輸入此文件的路徑並讓 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']
我想讓代碼獲取這些文件中的每一個,打開它們並將其所有內容放入一個巨大的列表中,而不僅僅是打印文件名。 有沒有辦法做到這一點?
如果您使用的是 Python3,則可以使用:
for filename in filename_list :
with open(filename,"r") as file_handler :
data = file_handler.read()
請注意,您將需要文件filename
中filename
的完整(相對或絕對)路徑
這樣,當您離開with
范圍時,您的文件處理程序將自動關閉。 這里的更多信息: https : //docs.python.org/fr/3/library/functions.html#open
附帶說明一下,為了列出文件,您可能需要查看glob並使用:
filename_list = glob.glob("/path/to/files/*.txt")
您應該為此使用文件打開。 在此處閱讀有關其高級選項的文檔
無論如何,這是一種方法:
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)
您可以使用文件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')
上面的代碼將從指定目錄( folderpath )中讀取.txt
所有數據並將其存儲在alldata.txt因此,您想要擁有那個長列表,如果需要,該列表現在存儲在 .txt 文件中,否則您可以去掉寫進程。
鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.