文件无法在Python脚本中写入

 蓝田学园赴嘉兴镇海吉林实践团队 发布于 2023-02-08 13:01

我的脚本无法正常工作,我无法弄清楚bug的位置,每次我想在Python中使用该文件时,我都使用open()函数打开文件,运行时会发出错误信号:

Traceback (most recent call last):
  File "my_example.py", line 26, in 
    doc.truncate()
IOError: File not open for writing

要运行它,我在终端中以这种方式运行它:

python my_example.py my_example_sample.txt

这是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?

有解决方案吗

程序所做的只是读取(读取())文件(打印文件),询问用户是否要删除文件(truncate())以及是否要写入文件(write()).

1 个回答
  • 默认情况下,open()打开以供阅读.如果要打开写入,则必须将open的第二个参数传递给特定的模式(例如,'w'用于写入).

    2023-02-08 13:05 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有