Python: 从另一个文件打印字符串

Python: printing strings from another file

我想调用一个文件,擦除它的数据,写入新行并打印它。 下面是我的程序及其输出。

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()

输出:

[] []

所以,你的错误(根据你的评论是它不允许你阅读)。

这是因为您尝试使用用于以写入模式打开文件的文件指针进行读取。

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:
    ...

所以添加 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', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"] ['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]