从python scrip中的文件夹读取.txt文件

2024-04-25 20:41:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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文件,所以我要执行上述操作。后来我想把我读到的东西打印出来。但是当我运行上面的程序时,我没有得到任何输出。有人能帮我一下那有什么错吗?


Tags: pathintxtforifosfilesusers
2条回答

那个

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规范化路径。你不需要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()

使用以下选项:

...  
f=open(os.path.join(subdir, file),'r')  
...

将分隔符/替换为\(Python2),\\(Python3)。

要读取特定行,可以使用linecache

import linecache
linecache.getline(filename, linenumber)

相关问题 更多 >