[英]Open files using For-loop (Python 3)
抱歉,我是Python 3的新手,我已經在這里一直在尋找答案,但是我找不到我問題的具體答案,而是我可能沒有問正確的問題。
我有一個名為test5.txt的文件,其中我寫了要使用Python打開/讀取的文件的文件名,即(test2.txt,test3.txt和test4.txt),這些txt文檔上都有隨機單詞。
這是我的代碼:
with open("test5.txt") as x:
my_file = x.readlines()
for each_record in my_file:
with open(each_record) as y:
read_files = y.read()
print(read_files)
但是可悲的是我遇到了錯誤: "OSError: [Errno 22] Invalid argument: 'test2.txt\\n'"
建議使用rstrip
而不是strip
-更好的安全和明確的。
for each_record in my_file:
with open(each_record.rstrip()) as y:
read_files = y.read()
print(read_files)
但這也應該可行,並且使用str.splitlines
方法可能更漂亮-請在此處查看此帖子。
with open("test5.txt") as x:
list_of_files = x.read().splitlines()
似乎each_record
包含換行符\\n
。 您可以嘗試先刪除文件名字符串,然后再將其作為文件打開。
with open("test5.txt") as x:
my_file = x.readlines()
for each_record in my_file:
with open(each_record.strip()) as y:
read_files = y.read()
print(read_files)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.