从 python 脚本中的文件夹读取 .txt 文件

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')  

zetysz 回答的是对的。 问题出在您提供的包含反斜杠的起始目录路径中。

您可以将其更改为正斜杠 / 而不是反斜杠 \,如下所示:

directory = os.path.normpath("C:/Users/sam/Desktop/pcm-audio")

或者您可以像这样使用双反斜杠引用它们:

directory = os.path.normpath("C:\Users\sam\Desktop\pcm-audio")

在这里也使用os.path.normpath to normalize the path. You dont need 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()