如何在Python中打开和编辑现有文件? [英] How to open and edit an existing file in Python?
问题描述
我一直在研究各种不同的程序来练习我的Python,其中最著名的是我自己选择的冒险游戏,到目前为止,它已有1000多行.最近,我一直在尝试从Python内部编辑文件,但似乎无法弄清楚.例如,如果我像这样将变量设置为用户输入:
input1 = raw_input("What is your favorite food?")
然后,假设我要将此文本保存到已经存在的.txt文件中,例如food.txt
.我该怎么办?
I've been working for a while now on a variety of different programs to practice my Python, the most notable being my choose-your-own-adventure game, which is well over 1000 lines so far. More recently, I have been trying to edit files from within Python, and I can't seem to figure it out. For instance, if I set a variable to a user input like so:
input1 = raw_input("What is your favorite food?")
Then, let's say I want to save this text to a .txt file that already exists, like food.txt
. How would I do that?
推荐答案
此链接也许会有所帮助,
# Open a file
fo = open("foo.txt", "a") # safer than w mode
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
这篇关于如何在Python中打开和编辑现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!