在w +模式下无法在python中读取文件

时间:2016-12-28 20:33:23

标签: python python-2.7

我是Python的新手,我目前正在学习文件操作。我无法读取我刚写入的文件。我正在使用w +模式。

另外请告诉我,我在

中做错了什么

textbuffer = str(“%r \ n%r \ n%r \ n”%input(),input(),input()) 评论说。

以下是代码段:

filename = '/home/ranadeep/PycharmProjects/HelloWorld/ex15_sample.txt'
target = open(filename,'w+')
target.truncate()

print("Input the 3 lines: ")
textbuffer = "Just a demo text input"
#textbuffer = str("%r\n %r\n %r\n" % input(), input(), input())
target.write(textbuffer)
# read not working in w+ mode
print(target.read())
target.close()

# read only mode
updated_target = open(filename,'r')
print(updated_target.read())

2 个答案:

答案 0 :(得分:3)

with open(file_name,"w+") as f:
    f.write("I love programming and i love python ")
    f.seek(0) #move cursor to the start of the file
    data=f.read()
    print(data)

答案 1 :(得分:1)

当您写入文件时,您开始阅读的行只发生在您写入的行之后。为此,您需要重置" head"回到文件的开头。

target.write("blah")

# This is new
target.seek(0)

print target.read() 
target.close()