3

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?

Elle Nolan
  • 379
  • 5
  • 8
  • 22

5 Answers5

4

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()
liuzhidong
  • 538
  • 3
  • 18
2

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"
tomasyany
  • 1,132
  • 3
  • 15
  • 32
1

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")
CyanogenCX
  • 414
  • 6
  • 17
  • Opening an existing file (that presumably OP wants to keep the contents of) in write mode is a bad idea, it wipes the existing content of the file. – Marius Dec 16 '14 at 03:07
  • @Marius maybe you shouldn't be so hasty with the down vote next time. opening it with the argument 'a' is allowing me to modify the text file. Maybe you would like to explain how this works if my understanding is incorrect? [Example for you](http://i.snag.gy/9hsN2.jpg) - I have shown that appending it can be done with 'a', and creating it new/opening new file can be done with 'w'. I don't see why you would downvote me. – CyanogenCX Dec 16 '14 at 03:14
  • Could you remove the downvote please? As you clearly hadn't read the whole answer. – CyanogenCX Dec 16 '14 at 03:17
  • Yes, 'a' mode is OK, but 'w' mode is not. OP says in their question that they already have a file called food.txt, if they started trying out your code they could have lost the contents of their file. – Marius Dec 16 '14 at 03:17
  • Not trying to lecture you about 'a' vs 'w' mode, my point is that if OP isn't as familiar with this stuff as you they could try to run your first line and lose their file, you should warn when giving potentially 'dangerous' code samples to people still learning to code. – Marius Dec 16 '14 at 03:20
  • He would have understood if he read the whole answer. And I'm pretty sure this question has been asked hundreds of times on stack overflow. And again, OP should know that good coding practices include keeping a copy of all original files and then to begin experimenting. OP never said he wanted to append to a file or not, he just said he had an existing file. So there is nothing wrong with my answer. – CyanogenCX Dec 16 '14 at 03:22
  • You all need to calm down. As you guessed, I'm not as familiar with this stuff as you guys, but I appreciate the time you all take to give me tips. Don't waste even more time fighting over something this stupid. – Elle Nolan Dec 16 '14 at 03:25
  • I am calm, just educating Marius on how wrong he is. Btw Drew, I hope you understand the distinction between using 'w' and 'a'. I hoped you picked that up from my answer. Also, next time I would recommend doing a quick google or stackoverflow search as this question has been asked many times. May I refer you to http://stackoverflow.com/questions/4706499/how-do-you-append-to-file-in-python – CyanogenCX Dec 16 '14 at 03:28
  • I found all the other tutorials, and none of it worked. That's why I asked, and this isn't working for me either and I have no idea why. But I do understand the difference between "w" and "a" mode - thanks! – Elle Nolan Dec 16 '14 at 03:29
  • How is this not working for you? What are you specifically doing? I'd like to help you solve this. – CyanogenCX Dec 16 '14 at 03:32
  • Well, at first I copied everything with different file names and such, but that didn't work so I literally copied and pasted this code, with a new file that was called "food.txt" and did all that and such. Copied and pasted. Still didn't work. – Elle Nolan Dec 16 '14 at 03:41
  • Can you tell me what the exact problem is you have to solve? I will try to code it in python and give it to you. – CyanogenCX Dec 16 '14 at 03:43
  • Nothing specifically, just have the user input something and record said thing in a file. – Elle Nolan Dec 16 '14 at 03:46
  • Try copying and pasting this code into an editor and then running it (through cmd or linux terminal I assume (if you need help with that ask)) http://ideone.com/N3j8h6 It gives an error on Ideone because I am not allowed to modify text files on the website. – CyanogenCX Dec 16 '14 at 03:50
  • @user2780354 Didn't work. I'm doing it on a mac, though. Could that have something to do with it? An app called CodeRunner. – Elle Nolan Dec 16 '14 at 20:28
  • I have no idea why it isn't working. here is me running it and the output. I'm not very hardware-savvy so I wouldn't know about the mac. Does it run without errors? Do you have python installed? Here is mine http://i.snag.gy/9hsN2.jpg – CyanogenCX Dec 16 '14 at 23:02
0

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. :)

Kamyar Ghasemlou
  • 859
  • 2
  • 9
  • 24
0

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)
Alexey Shrub
  • 1,216
  • 13
  • 22