用于文件写入的Python raw_输入

2024-09-30 08:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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()

我正在创建的脚本应该能够写入用户通过原始输入定义的文件。上面的内容可能在核心上是错误的,可以接受建议。在


Tags: to代码reyoubethisfilewrite
2条回答

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

但实际上,您可以使用下面给出的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()

注意:如果新文件不存在,此方法将创建新文件。如果要检查文件是否存在,可以使用操作系统模块,如下所示:

^{pr2}$

相关问题 更多 >

    热门问题