使用statemnt打开文件而不是将open打开到变量

时间:2018-01-16 19:48:14

标签: python python-3.x

我正在尝试学习如何通过python3处理文件 所以我达到了这个问题,我无法知道我的代码的哪一部分不起作用! 我试图用不同的方式两次打印同一文件的内容,我相信我在这里犯了多个错误,

file = open("exp.py", "w")
file.write("this has been written to a file")#it wil
print(file.read())
file.close()
print('first sanad')

with open("exp.py") as f:
        print(f.read())
        #it will be closed automatically
        print('second sanad')
        # f is a temp variable within the block

错误

36-32\writing to a file with w.py", line 3, in <module>
    print(file.read())
io.UnsupportedOperation: not readable

1 个答案:

答案 0 :(得分:0)

第一个问题是,您是以只写方式打开文件,而不是像这样读写:

file = open("exp.py", "r+") # "r+" instead of "w"

[...]

with open("exp.py") as f: ## here you should also specify "r+" if you plan to write to the file

[...]

请注意:

在文件上调用.read()后,您必须调用.seek(0),否则它将在第二次打印空字符串。解释here