[英]reading a .txt file from a folder in python script
directory =os.path.join("C:\\Users\\Desktop\\udi\\pcm-audio")
for subdir, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".txt"):
f=open(os.path.join(subdir, file),'r')
a = f.read()
if re.findall('\"status_code\": 0', a):
print('Valid one')
else:
print('Invalid')
f.close()
我只需要從該文件夾中讀取一個.txt文件,所以我如上所述。 稍后,我嘗試打印我閱讀的內容。 但是,當我運行上述程序時,我沒有得到任何輸出。 有人可以幫我這是什么錯誤嗎?
使用以下內容:
...
f=open(os.path.join(subdir, file),'r')
...
將分隔符/
替換為\\
(Python2), \\\\
(Python3)。
要讀取特定行,可以使用linecache
:
import linecache
linecache.getline(filename, linenumber)
該
f=open(os.path.join(subdir, file),'r')
澤蒂斯回答的是對的。 問題出在您提供的包含反斜杠的起始目錄路徑中。
您可以將其更改為正斜杠/,而不是反斜杠\\,如下所示:
directory = os.path.normpath("C:/Users/sam/Desktop/pcm-audio")
或者,您可以使用雙反斜杠將其引用為如下形式:
directory = os.path.normpath("C:\\Users\sam\\Desktop\\pcm-audio")
還可以使用os.path.normpath標准化路徑。 您不需要這里的os.path.join ,因為您沒有加入任何東西。
所以這應該工作:
import os
directory = os.path.normpath("C:/Users/sam/Desktop/pcm-audio")
for subdir, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".txt"):
f=open(os.path.join(subdir, file),'r')
a = f.read()
print a
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.