Notes

Opening and Writing to Files in Python

Edit on GitHub

Python
3 minutes

Our bio.txt contains

Name: Aamnah
Age: 26
Location: Dubai
Gender: Female

To open it in Python:

1file = open('bio.txt')

The function open() can take two parameters, one is the path of the file
bio.txt (required). The other is mode (optional) which specifies the mode in which the file is opened, for example w+b. The default mode is r which means open for reading in text mode.

The w flag opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

You can use open() with the w flag to create a new file or overwrite an existing one.

The file path could also be a URL.

Get it to read it line by line

1for line in file:
2    print line    

This will output:

Name: Aamnah

Age: 26

Location: Dubai

Gender: Female

To remove the extra space at the end of the line, use the following code:

1for line in file:
2    print(line, end = '')

The output now will be

Name: Aamnah
Age: 26
Location: Dubai
Gender: Female

Writing to the open file

Once you have the file open, you can use any of the following commands to write to the file

  • write('stuff') – Writes “stuff” to the file.
  • close – Closes the file. Like File->Save.. in your editor.
  • read – Reads the contents of the file. You can assign the result to a variable.
  • readline – Reads just one line of a text file.
  • truncate – Empties the file. Watch out if you care about the file.

For example

 1print "Opening the file..."
 2target = open('bio2.txt', 'w')
 3
 4print "Emptying the file!"
 5target.truncate()
 6
 7print "Writing to the file.."
 8target.write('URL: http://aamnah.com')
 9target.write('\n')
10target.write('Skills: Web Developer')
11target.write('\n')
12target.write('Learning: Python')
13target.write('\n')
14
15print "Closing and saving the file."
16target.close()  

You will now have a file called bio2.txt with your written data. Remember, the w flag in open() creates or overwrites a file.

Example of writing to file with system input

Getting file details

The open function creates a file object. You can get various information related to that object using the following attributes:

AttributeDescription
closedReturns true if file is closed, false otherwise.
modeReturns access mode with which file was opened.
nameReturns name of the file.
softspaceReturns false if space explicitly required with print, true otherwise.

For example:

1#!/usr/bin/python
2
3# Open a file
4file = open("bio.txt", "wb")
5print "File name: ", file.name
6print "Is the file open? : ", file.closed
7print "Opening mode : ", file.mode
8print "Softspace flag : ", file.softspace    

This would produce the following result:

File name:  bio.txt
Is the file open? :  False
Opening mode :  wb
Softspace flag :  0

Writing CSV files

1file = open("registrants.csv", "a") # create/open a file and append to it
2writer = csv.writer(file)
3writer.writerow((request.form["name"], request.form["dorm"])) # values here are coming from a Flask template
4file.close()
  • w writes and overwrites. it clobbers, meaning it’ll keep creating new files over the last one.
  • a appends to the file. meaning it’ll add stuff to the end of the file you mention.
  • csv module comes built-in with Python
  • writerow() takes care of sanitizing input (eliminating commas and apostrophes and such)

Related