现在,我有file.py,它在text.txt中输出单词“Hello”。
f = open("text.txt")
f.write("Hello")
f.close()
我想做同样的事情,但我想在Python文件中打印“Hello”这个词。说我想做这样的事情:
f = open("list.py")
f.write("a = 1")
f.close
当我打开文件list.py时,它是否有一个值为1的变量a?我该怎么做呢?
如果要在文件末尾附加新行
with open("file.py", "a") as f:
f.write("\na = 1")
如果要在文件开头写一行,请尝试创建一个新行
with open("file.py") as f:
lines = f.readlines()
with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))
with open("list.py","a") as f:
f.write("a=1")
如你所见,这很简单。您必须以写入和读取模式打开该文件(a)。使用open()方法也更安全,更清晰。
例:
with open("list.py","a") as f:
f.write("a=1")
f.write("\nprint(a+1)")
list.朋友
a=1
print(a+1)
list.py的输出:
>>>
2
>>>
如您所见,list.py中有一个变量,等于1。
我建议您在打开文件进行阅读,书写等时指定打开模式。例如:
阅读:
with open('afile.txt', 'r') as f: # 'r' is a reading mode
text = f.read()
写作:
with open('afile.txt', 'w') as f: # 'w' is a writing mode
f.write("Some text")
如果您使用“w”(写入)模式打开文件,将删除旧文件内容。为避免存在附加模式:
with open('afile.txt', 'a') as f: # 'a' as an appending mode
f.write("additional text")
欲了解更多信息,请阅读documentation。