我有以下代码:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open('targetfile' , 'w')
print "What do we write in this file?"
targetfilefound.write("hello this is working!")
targetfilefound.close()
我创建的脚本应该能够写入用户通过raw_input定义的文件。以上可能是错误的核心,对建议持开放态度。
答案 0 :(得分:0)
正如其他人所指出的那样,从目标文件中删除引号,因为已将其分配给变量。
但实际上,您可以使用下面给出的open,而不是编写代码
with open('somefile.txt', 'a') as the_file:
the_file.write('hello this is working!\n')
在上述情况下,处理文件时不需要进行任何异常处理。当发生错误时,文件光标对象会自动关闭,我们不需要显式关闭它。即使它写入文件成功,它也会自动关闭文件指针引用。
Explanation of efficient use of with from Pershing Programming blog
答案 1 :(得分:0)
根据脚本打印的内容判断,您可能希望用户输入应该打印到文件的内容,以便:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
注意:如果新文件不存在,此方法将创建新文件。如果要检查文件是否存在,可以使用os模块,如下所示:
import os
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
if os.path.isfile(targetfile) == True:
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "File does not exist, do you want to create it? (Y/n)"
action = raw_input('> ')
if action == 'Y' or action == 'y':
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "No action taken"