[英]File not open for writing in Python script
My script is not working, I can't figure out where the bug is, I have opened the file with the open() function each time I want to work with the file in Python , and when running it signals this error: 我的脚本无法正常工作,我无法弄清楚错误在哪里,每次我想在Python中使用文件时都使用open()函数打开文件,并且在运行该文件时会提示此错误:
Traceback (most recent call last):
File "my_example.py", line 26, in <module>
doc.truncate()
IOError: File not open for writing
To run it I run it this way in the Terminal: 要运行它,我在终端中以这种方式运行它:
python my_example.py my_example_sample.txt
Here's the Python Script (code) : 这是Python脚本(代码):
from sys import argv
#from os.path import exists
script, filename = argv
print "The name of this program is %s" % script
print "The name of the file you want to read is %s" % filename
print "Press ENTER if you want to read the selected document."
print "Press CTRL-C to cancel."
raw_input('>')
print "%s :" % filename
doc = open(filename)
print doc.read()
#doc.close()
erase_file = raw_input("Do you want to erase the file %s Y/N? : " % filename)
if erase_file == "Y":
doc = open(filename)
print "Truncating the file..."
doc.truncate()
print "Done, truncated."
#doc.close()
else:
print "That's okay!"
write_file = raw_input("Do you want to write in the file %s Y/N? : " % filename)
if write_file == "Y":
doc = open(filename)
print "I'm going to ask you to type in what you like to write in the file %s
(limited to 3 lines)" % filename
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Perfect! writing in..."
doc.write(line1)
doc.write('\n')
doc.write(line2)
doc.write('\n')
doc.write(line3)
doc.write('\n')
print "Done!"
doc.close()
else:
print "Ok, see you later!"
doc.close()
# add copy and exists? features?
Any solution? 有什么办法吗?
What the program does is simply reading ( read() ) a file (printing the file) , ask the user if he wants to erase the file ( truncate() ) and if he wants to write in it ( write() ) . 程序所做的只是读取( read() )文件(打印文件) ,询问用户是否要擦除文件( truncate() ),以及是否要写入文件( write() )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.