2014-10-20 130 views
0

我有一个需要逐一打开的数据库文件列表,并且将Python is a great language.\nYeah its great!!写入所有文件。if语句后文件没有打开

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

1.txt 
2.txt 
3.txt 

我的代码:

for files in cursor.fetchall():    
    sfile= files[1] 
    if os.path.exists(os.path.join(path,sfile)): 
      with open(sfile,'r') as f: 
       f.write("Python is a great language.\nYeah its great!!\n"); 
       f.close() 

错误:

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

请帮我纠正我的错误!

+2

你正在检查'os.path.join(path,sfile)',但是打开'sfile'(在'r'ead模式下)。 – jonrsharpe 2014-10-20 16:28:53

回答

1

您应该指定您检查上面一行的完整路径。你也需要打开'w'来写,'r'是供阅读。您也不需要close您使用with打开的文件。试试这个

for files in cursor.fetchall():    
    sfile= files[1] 
    fullPath = os.path.join(path,sfile) 
    if os.path.exists(fullPath): 
      with open(fullPath ,'w') as f: 
       f.write("Python is a great language.\nYeah its great!!\n"); 
+0

如果我只想单独读取文件,即使在删除写入方法后,我也会得到相同的错误。因为我的目标是单独阅读文件。 – 2014-10-20 16:37:56

+0

如果你的目标是只读,你不应该写入文件,然后 – Parker 2014-10-20 17:17:12