Python raw_input 用于文件写入

Python raw_input for file writing

我有以下代码:

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 定义的文件。以上内容可能存在核心问题,欢迎提出建议。

正如其他人所指出的,从目标文件中删除引号,因为您已经将其分配给了一个变量。

但实际上,您可以使用 with 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

根据脚本打印的内容判断,您可能希望用户输入应该打印到文件中的内容,因此:

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"