Python: Simple File Read and Write

python
Though there are a lot of resources out there for Python,and great books, rarely do you find a simple reference guide that helps you navigate the basics. I found that there was not a lot of reference material to help you do the simple things, if you didn’t know what to look for.

This little guide will focus on the basics of reading and writing files in python..

First we are going to focus on reading from files. Open up your Python shell,
or IDE.

To open a file/file object :

open(filename,mode)
  1. filename can be a file or path to a file
  2. mode can be any of the following
  1. ‘r’ for reading
  2. ‘r+’ for reading and writing
  3. ‘w’ for writing
  4. ‘a’ for appending
  5. both read and write modes also have a ‘b’ option for binary reading and writing (‘rb’, or ‘wb’)

Ex:
myInput = open('myfile.txt','r')

This command will open the file “myfile.txt” in the current
directory, in “read” mode. You can access the methods of this file
using the ‘myInput’ variable. In the example, the open command will
open the file indicated in the first argument(‘myfile.txt’).
This argument can be a file, or the path to a file. The second
argument, is the file mode.

Once you have a file handle(myInput), you can work with that
file, depending on the mode you opened it with. We can now start
reading data from our file.

Ex:
s = myFile.read() Will read entire file into a string
s = myFile.read(N) Will read N bytes (1 or more) from file
s = myFile.readline() Will read next line into string until end of line
L = myFile.readlines() Will read entire file into a list of strings

 

22 thoughts on “Python: Simple File Read and Write

  1. Hi, I have opened my file I have manipulated and I want save this new change in the other directory. At least I know that I should be use ' r ' for reading and ' w ' command for writing, but I do not know how I can make connection between readings and manipulate file and writing this manipulation in the other file.
    Best Regards
    Reza _ Finland

  2. All you need to do is specify the location of the file you want to save to.

    So when opening the second file, specify the directory then.
    Example on win32:
    file = open(“my_dir\newfile.txt”,”w”)
    Example on *nix :
    file = open(“my_dir/newfile.txt”,”w”)

    This will create the new file in the directory “my_dir” assuming the directory exists in the same folder as your python script. You can also specify an absolute file path as well.

  3. Thank you Daniel, another problem:
    x = [0,1,2,3]
    GeneCode = ['AAAA','AAAC','AAAG','AAAT']
    def Li_to_GC(x):
    for i in x:
    print GeneCode[i],
    Li_to_GC(x)

    How can convert the result to the list or string?

  4. Well,
    I would argue that the input is a list already. If you are wanting to return a subset of the GeneCode list, I would do the following. There are more graceful ways to achieve this, but this method shows you the logic involved.

    x = [0,1,2,3]
    GeneCode = ['AAAA','AAAC','AAAG','AAAT']

    def Li_to_GC(x):
    newList = [GeneCode[i] for i in x]
    return newList

    print Li_to_GC(x)

    In this case, you can then pass any numeric list to LI_to_GC and get the corresponding Genecodes list back.
    I would check out this great List comprehension article here, and you can learn more. http://effbot.org/zone/python-list.htm

  5. Hi,
    I am opening a file in r+ mode. I have a problem in this. If I first write in a file and then read the same file it is working fine. But some junk characters are added to the end of the string.
    Also one more problem if I read it first say using readline function and then write it, the write operation doesn't happen. Any idea what might be the problem?

  6. I agree with your first statements, there is quite a bit of python help out there, but hard to get to the simple stuff. Am tryng to open a txt file, pull certain parts out, and then write to a new csv….get bits of it, but not the whole process, any help would be great, thanks

  7. I am writing a script to save the id while commiting to server.
    file = open(“test.txt”, “w”)
    file.write(id)

    But while committing ,it is not writing to test.txt

  8. Hi Rev,

    Is id an integer or a string? You can try this to convert to a string and see if it works for you:

    file = open(“test.txt”, “w”)
    file.write(str(id))

  9. The code was like this :

    id=str(bid)
    file = open(“test.txt”, “w”)
    file.write(id)

    It was not working

  10. Hey Rev,

    At this point you need to start looking at what the errors are when you execute this code. My guess is that there is a permissions problem or something similar. If you can include any errors you are seeing , it will help to identify the problem. Good luck.

  11. Thanks Daniel

    No errors were shown.What can do for this permission problem?

    i have tested this scipt in cmd prompt with a sample text file containing id,then it got written to the file.

  12. Ok I have a question on how to write this python script. I am suppose to write a python code that reads the file y-z TEXT CS-365.txt that prints a two item line for each input line; the first item is to be the input line number; the second item is to be the amount following the word “due” on that line.

    This is the input file
    Suzette Jones, begin 01/02/03, end 02/03/04
    Michael Smith, begin 12/01/90, end 03/07/99
    The Henderson Family, begin 11/3/88, paid 293.77, due 123.45
    Doreen Mitchell, begin 09/25/94, due 345.67, paid 133.45

    Josh Dominic, begin 06/21/96 due 41.51
    Shannon Gaspar, begin 03/21/02, paid 99.99, due 1001.01
    Jennifer Allene Pendergast, end 03/31/03

  13. Hey there,

    I am trying to open and read a file from my computer and I am trying to code how to do this in python. What I am so far is infile = open(bloodsample,’r’)
    data = infile.read()
    Am I in the ball park?

    Is this in my main() function?

    Thank you <3

  14. Hi Francine.

    This can be in your main() function if you like. It probably makes sense to create a separate function to manage it, but that isn’t necessary.

    Your code is correct assuming the following.
    1. That “bloodsample” is a variable that references the name of the file you want to open. If your file name IS “bloodsample”, then you need to wrap it in quotes to open it.
    2. The file is in the same directory as the python code you are executing.

    You can verify you are passing the file contents correctly by adding a simple print statement after you read the file into the “data” variable.
    Example:

    infile= open(bloodsample,'r')
    data = infile.read()
    print data

  15. Hello, I want to read images in a set of files and then filter out the duplicated images. can you help on this please.

  16. Hello, I have a text file saved on my desktop, am using windows, this file contains name of countries. What i want to achieve is that i want to open it in python sort it alphabetically then write it out to another file.

    Please how can i achieve this?

    Thanks

  17. hello every body
    I want write in file and I want save this new change. I input name from user and i want to write name in file but i can’t :((

  18. Hi, i’m new in python, I have a text file (sample below) and want to update only a record like Jojo , I want to add 100 to make it 300,how will I do that in python? Thanks

    Jeff 100 T
    Jojo 200 P
    Joy 300 F

  19. im trying to make a program that when i open it it will create a text document on the desktop,
    iv being trying to make this for over a month, and i managed to make it but my computer crashed and nothing was saved.

    if you have the time can you please try to figure it out,
    thank you tel to daniel

Leave a Reply