gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:35:45 24 4
gpt4 key购买 nike

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

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

关于Python:从另一个文件打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com