Reputation: 399
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?
Upvotes: 3
Views: 34944
Reputation: 1314
I find beautiful module for this task - in_place, example for Python 3:
import in_place
with in_place.InPlace('data.txt') as file:
for line in file:
line = line.replace('test', 'testZ')
file.write(line)
Upvotes: 0
Reputation: 859
your question is a bit ambiguous, but if you are looking for a way to store values for later use and easy retrieval; you might want to check ConfigParser. :)
Upvotes: 0
Reputation: 1242
The open()
built-in Python method (doc) uses normally two arguments: the file path and the mode. You have three principal modes (the most used): r
, w
and a
.
r
stands for read and will make the open("/path/to/myFile.txt", 'r')
to open an existing file and to only be able to read it (not editing), with myFile.readlines()
or other methods you can find in this documentation.
w
stands for write and will not only erase everything the file had (if it existed), but let you write new stuff on it through myFile.write("stuff I want to write")
.
a
stands for append and will add content to an existing file without erasing what could have been written on it. This is the argument you should use when adding lines to non empty files.
You must not forget to close the file once you have finished working with it with myFile.close()
because it is only at that point where all the changes, updates, writings, are done.
An 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 file contents were something 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"
Upvotes: 2
Reputation: 548
this link maybe will be help,
the 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()
Upvotes: 4
Reputation: 404
To open a file named food.txt
f = open('food.txt', 'w')
To write as a new line:
f.write("hello world in the new file\n")
remove the \n if you want it on the same line.
to read it you can do for example
print(f.read())
If you wish to append:
with open('food.txt', "a") as f:
f.write("appended text")
Upvotes: 1