【问题标题】:text file is not read from a list of files文本文件不是从文件列表中读取的
【发布时间】:2014-10-20 18:00:17
【问题描述】:

不重复:file not opens after if statement

我有一个来自数据库的文件列表,需要一个一个打开并读取所有文件。

问题:即使文件存在,我也无法打开和读取文件。 files 包括:

1.txt
2.txt
3.txt

我的代码:

path=r'C:\Python27' 
for files in cursor.fetchall():            
     sfile= files[1]
     if os.path.exists(os.path.join(path,sfile)): 
           with open(sfile,'r') as f:
                if 'cat' in f:
                    print 'meow'

错误:

    with open(sfile,'r') as f:
IOError: [Errno 2] No such file or directory: '1.txt'
>>>

请帮我纠正我的错误!

【问题讨论】:

    标签: python python-2.7 io


    【解决方案1】:

    您还需要在调用open 时使用os.path.join,就像调用os.path.exists 一样。

    另外,您需要调用file.read 来获取文件内容。

    path = r'C:\Python27'  # NOTE: r'raw string literal': \ mean \ literally
    for files in cursor.fetchall():            
         sfile = files[1]
         spath = os.path.join(path, sfile)
         if os.path.exists(spath):
             with open(spath) as f:
                 if 'cat' in f.read():
                     print 'meow'
                 # OR
                 # if any('cat' in line for line in f):
                 #     print 'meow'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2015-04-19
      • 2014-05-11
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多