[英]Unable to read file in python in w+ mode
我是 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())
当您写入文件时,您开始读取的行仅出现在您写入的行之后。 为此,您需要将“头部”重置回文件的开头。
target.write("blah")
# This is new
target.seek(0)
print target.read()
target.close()
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.