[英]How can I open a series of files (PNGs) from a specified directory (randomly) using Python?
[英]How I can simulateneously sort and unique files from directory using python?
我正在嘗試在一個文件中對30個大小不同的文件進行排序和唯一化。
每個文件包含一行,並由換行符分隔。 這意味着文件的每一行都有簡單的文本。
這是我嘗試嘗試的方法:
lines_seen = set() # holds lines already seen
outfile = open('out.txt', "w")
for line in open('d:\\testing\\*', "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
文件夾名稱正在testing
,它包含30個不同的文件,我正在嘗試將其合並到文件out.txt
。 輸出將是排序並唯一的文本,寫在輸出文件的每一行上。
好吧,我認為這很容易,如果我寫d:\\\\testing\\\\*
,它將從該文件夾中讀取文件。 但是我得到了錯誤:
Traceback (most recent call last):
File "sort and unique.py", line 3, in <module>
for line in open('d:\\testing\\*', "r"):
OSError: [Errno 22] Invalid argument: 'd:\\testing\\*'
我想知道如何擺脫這個錯誤,並有效地將所有文件處理成一個輸出而不會失敗。
請注意:RAM為8 GB,文件夾大小約為10 GB。
您只需要使用os.listdir
遍歷所有文件。 像這樣:
lines_seen = set() # holds lines already seen
outfile = open('out.txt', "w")
path = r'd:\testing'
for file in os.listdir(path): #added this line
current_file = os.path.join(path, file)
for line in open(current_file, "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.