Read and Write File

Reading files

Python has built in support for reading and writing files. The function readlines() can be used to read the entire files contents:

#!/usr/bin/env python
 
filename = "readme.txt"
 
with open(filename) as fn:
    content = fn.readlines()
 
print(content)

Content will contain a list of all strings in the file.

python read file

Writing files

To write files, you can use this code:

!/usr/bin/env python
 
f = open("output.txt","w")
f.write("Pythonprogramminglanugage.com, \n")
f.write("Example program.")
f.close()

On the first line we open the file for writing. The parameter “w” tells Python we want to open the file for writing. The write() calls write data into the file. Finally we close the file.

python-write-file
The file created by the Python program.


Dictionary
Modules

15 thoughts on “Read and Write File

  1. Reply
    JohnDoe - March 22, 2016

    Why are you using
    ” with ** as **: ” for reading
    and
    ” open() and close() ” for writing
    ?

    1. Reply
      admin - March 29, 2016

      I create the object f, which I later use for the write() method.

      1. Reply
        linger3152 - May 27, 2016

        Is it possible that the f is invalidate as open failed ?

        1. Reply
          admin - July 22, 2016

          Yes, if file does not exist

  2. Reply
    Metalsand - April 19, 2016

    It might be nice to include an explanation of “with” in this part. I had to look it up, and it appears to be a generalization of the ‘for’ statement that is unique to Python.

    From what I’ve seen, these are tutorials for experienced programmers as to the differences between Python and other languages and while a long drawn out explanation would defeat the purpose of brevity, a short sentence explaining the reason for using ‘with’ and contrasting with ‘for’ should suffice.

    While I’m typing, I also would like to say how much I appreciate these tutorials, they are exactly what I needed and HOLY CRAP DO I LOVE PYTHON IT IS SO AWESOME.

  3. Reply
    Jonathan - June 10, 2016

    Is there any way to read binary files with this type of code?

    1. Reply
      admin - June 10, 2016

      This code will read a file line by line, where a line is separated by a newline character. To read binary files you can use this code:

      with open(fileName, mode='rb') as file:
      fileContent = file.read()

      1. Reply
        raju bhai - July 21, 2016

        how to read the .DAT file (binary data of Image) in python. And i need to convert it to .TIFF(or .JPEG) file. It will be very helpful if i get an answer.

        Thanks in advance

          1. raju bhai - July 22, 2016

            hello,
            Thanks. Actually i have an .DAT file which is 4 dimensional image( Of Type FLOAT and Size of 104MBytes. I am not able to convert using PIL. Could you please help in converting it to .JPEG or :TIFF file.
            Thanks in advance

          2. admin - July 26, 2016

            Is it raw data? what is the data format?

  4. Reply
    I.V. - July 15, 2016

    When I launch this, I receive following error message:

    $ python read_file.py
    File “read_file.py”, line 3
    with open(filename) as fn:
    ^
    SyntaxError: invalid syntax

    Can it be related with the Python version?
    I have 2.4.3

    1. Reply
      admin - July 22, 2016

      Yes, the with keyword is included in version 2.5.2 and higher

  5. Reply
    alfred - December 29, 2016

    how to rename file?

    1. Reply
      admin - January 19, 2017

      you can use the os module for that. os.rename(src, dst)

Leave a Reply

Your email address will not be published. Required fields are marked *