我想调用一个文件,删除它的数据,写新行并打印它。 以下是我的程序及其输出。
from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()
输出:
[] []
答案 0 :(得分:2)
所以添加seek(0)就可以完成这项工作。 seek(0)将指针设置在开头。 这是工作代码:
from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
text.seek(0)
new = text.read()
text.seek(0)
old = text.readlines()
print "%s" %(new)
print old
text.seek(0)
print text.readlines()
text.close()
输出:
哎 在遇到你之前我做得很好 我喝得太多,这是一个问题,但我没关系
[' hey \ n','在我见到你之前我做得很好\ n',"我喝得太多而这是一个问题但我没关系\ n"] [' hey \ n','在我见到你之前我做得很好\ n',"我喝得太多而且这是一个问题,但我和# 39; m okay \ n"]
答案 1 :(得分:1)
所以,你的错误(通过你的评论是它不会让你阅读)。
这是因为您尝试使用用于在写入模式下打开文件的文件指针进行读取。
from sys import argv
string, filename = argv
with open(filename, 'w') as text:
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
with open(filename, 'r') as text:
...