当我使用 python open(filename, 'w+')
写入文件时,除了新的文本。 Python 2.7.3
from sys import argv
script, filename, random = argv
my_file = open(filename, 'w+')
added_line = raw_input("Type what you want to add: ")
my_file.write(added_line)
print my_file.read()
my_file.close()
我正在自学并练习打开和写入文件(我想这很明显)。我可以让程序运行并提示我输入新文本。我还尝试了 open(filename, 'a')
。
我错过了什么?
谢谢。
最佳答案
我尝试使用 w
选项打开文件,据我所知,如果您使用 w
选项打开文件,您只能写入文件,所以你不能运行 read()
方法。事实上,w+
使您能够读写。 (请注意,'w+' 会截断文件)。 r+
打开文件进行读写。
my_file.seek(0)
在读取之前返回到文件的顶部,否则你只会读取一个空字符串。
为我工作。
关于python-2.7 - Python--写入文件添加空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12600982/