if语句后文件无法打开

时间:2014-10-20 16:26:54

标签: python file

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

问题:即使文件存在,我也无法打开文件。 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'
>>>

请帮我纠正错误!

1 个答案:

答案 0 :(得分: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");