How to open and edit an existing file in Python?

I’ve been working on various programs for some time to practice Python, the most famous of which is my adventure game, which today has more than 1000 lines. More recently, I tried to edit files from Python, and I cannot figure it out. For example, if I set a variable for user input as follows: input1 = raw_input("What is your favorite food?") Then, say, I want to save this text in a .txt file that already exists, for example food.txt . How can I do it?

+2
source share
4 answers

this link may help

code such as

 # 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() 
0
source

The built-in Python method open() ( doc ) usually uses two arguments: the file path and . You have three main modes (most commonly used): r , w and a .

  • r means reading and will open("/path/to/myFile.txt", 'r') open an existing file and be able to read it (without editing) using myFile.readlines() or other methods that you can find in this documentation .

  • w means write and will not only erase all files (if they exist), but also allow you to write new things through myFile.write("stuff I want to write") .

  • a means adding and adding content to an existing file without deleting what might have been written on it. This is an argument to use when adding lines to non-empty files.

You should not forget to close the file after completing work with it using myFile.close() , because it is only at the moment when all changes, updates, records are completed.

A small snippet for adding a line:

 f = open("/path/to/myFile.txt", 'a') f.write("This line will be appended at the end") f.close() 

If the contents of the file were like

 "Stuff Stuff which was created long ago" 

Then the file after the code looks like

 "Stuff Stuff which was created long ago This line will be appended at the end" 
+1
source

your question is a bit ambiguous, but if you are looking for a way to store values ​​for later use and simple retrieval; you can check out ConfigParser . :)

0
source

To open a file called food.txt

 f = open('food.txt', 'w') 

To write as a new line:

 f.write("hello world in the new file\n") 

delete \ n if you want it to be on the same line.

to read it you can do for example

 print(f.read()) 

If you want to add:

 with open('food.txt', "a") as f: f.write("appended text") 
-1
source

All Articles