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

标签 python string python-2.7 file readfile

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

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/

相关文章:

python - "is"在 python 中如何工作?

从 R 中的字符串列中删除字符串列表

连续 scanf 正在添加字符串

Python 2.7 BeautifulSoup,电子邮件抓取

python - 使用 PyMongo 将 Pandas 数据框插入 mongodb

python - 使用 numba 在 int_s 数组中查找 numpy.int_

python - 如何使用Python从txt文件中删除特殊字符

python - 将数字应用于字符串的序列生成

python - 如何让 Python 的 multiprocessing Queue 的 .empty() 方法返回正确的值?还是替代品?

javascript - Android转义JavaScript字符串