[英]File not found error, even though file was found
使用以下代碼:
for root, dirs, files in os.walk(corpus_name):
for file in files:
if file.endswith(".v4_gold_conll"):
f= open(file)
lines = f.readlines()
tokens = [line.split()[3] for line in lines if line.strip()
and not line.startswith("#")]
print(tokens)
我收到以下錯誤:
追溯(最近一次通話最近):corpus_reading_pos中的文件“ text_statistics.py”,第28行(corpus_name,選項)corpus_reading_pos中的文件“ text_statistics.py”,行13,f =打開(文件)FileNotFoundError:[Errno 2]否此類文件或目錄:“ abc_0001.v4_gold_conll”
如您所見,該文件實際上已經找到了,但是當我嘗試打開該文件時,...找不到它?
編輯:使用此更新的代碼,它在讀取7個文件后停止,但是有172個文件。
def corpus_reading_token_count(corpus_name, option="token"):
for root, dirs, files in os.walk(corpus_name):
tokens = []
file_count = 0
for file in files:
if file.endswith(".v4_gold_conll"):
with open((os.path.join(root, file))) as f:
tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")]
file_count += 1
print(tokens)
print("File count:", file_count)
file
只是不帶目錄的文件,該root
位於代碼的root
中。 嘗試這個:
f = open(os.path.join(root, file)))
另外,您最好使用with
來打開文件,而不要使用file
作為變量名,以免遮蓋內置類型。 另外,從您的評論來看,您可能應該擴展標記列表(使用+=
代替=
):
tokens = []
for root, dirs, files in os.walk(corpus_name):
for filename in files:
if filename.endswith(".v4_gold_conll"):
with open(os.path.join(root, filename))) as f:
tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")]
print(tokens)
您必須將root
與文件名連接起來。
for root, dirs, files in os.walk(corpus_name):
for file in files:
if file.endswith(".v4_gold_conll"):
with open(os.path.join(root, file)) as f:
tokens = [
line.split()[3]
for line in f
if line.strip() and not line.startswith("#")
]
print(tokens)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.