2015-12-16 45 views
0
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文件,所以我如上做。后来我试图打印我读的东西。但是当我运行上述程序时,我没有得到任何输出。有人能帮助我,那是什么错误?阅读从一个文件夹中的.txt文件的Python脚本

回答

0

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() 
+0

它正在使用双斜杠。谢谢:)你能告诉我如何从.txt文件读取特定的行吗? –

+0

要从文件中读取行,可以遍历文件对象。这是内存有效率,快速,并导致简单的代码: '在行f: 打印行,' [阅读更多](https://docs.python.org/2/tutorial/inputoutput.html)搜索readline – klaas

+0

示例:如果.txt文件为200行.txt。如果我想在.txt文件中读取状态码== 0的特定行,那么该怎么做?我修改了我的问题。 –

1

使用以下命令:

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

\(Python2)更换分离/\\(Python3)。

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

import linecache 
linecache.getline(filename, linenumber) 
+0

这是行不通的。只是得到一个空的屏幕。我无法看到屏幕上的任何内容。 –

+0

它正在使用双斜杠。 ty :)你能告诉我如何从.txt文件中读取特定的行吗? –

+0

如果我在.txt文件中查找称为状态码== 0的单词。将会有这么多的.txt文件如果行号在不同的.txt文件中不同。那么该怎么办? –