How to Read and Write To/From Files in Python

Submitted by: 
Language: 
Visitors have accessed this post 312 times.

Introduction:
In this tutorial, we are going to be covering handling files in Python.

Generic:
To read or write from/to a file, we first need to create a stream. To do this we use the Python function 'open' which takes two parameters, the file, and the mode. The file should a file name (including directory location if it is not in the same directory as the current program) as a string, while the mode should also be a string. Don't forget to replace any backslashes in the directory with two backslashes to avoid Python escape character problems. The modes can be as follows...

r Read
w Write
a Append
r+ Read from and write to a text files.
w+ Write and read from a text file.
a+ Append and read from a text file.

So to open a file named 'leaderboard.txt' in the current directory for reading purposes, we use...

  1. readFile = open("leaderboard.txt", "r");

Or to open for writing purposes, we can use...

  1. writeFile = open("leaderboard.txt", "w");

Reading:
We can output the next line of a text file using .readline()...

  1. print(readFile.readline());

Python saves the current line that has been modified within the open variable, to reset back to the top of a file, close the stream and re-open it using...

  1. readFile.close();
  2. readFile = open("leaderboard.txt", "r");

Or we can read all the lines from the file at once using readlines, put them in a tuple, and output them one by one...

  1. allLines = readFile.readlines();
  2. for line in allLines:
  3. print(line);

We could also use the read function which takes one parameter of the ending character index. It returns each character from the current point in the file to the chraracter index...

  1. print(readFile.read(2));
  2. print(readFile.read(16));

Writing:
Next we can write to text files. First we could use write which simply overwrites any pre-existing text in the file and replaces it with the specified string...

  1. writeFile.write("Hey there!");

We could also use writelines to append a list of strings to the bottom of the file...

  1. myLines = ("This ", "is ", "a ", "new ", "line.");
  2. writeFile.writelines(myLines);

We first make a new tuple named myLines which contains five strings which concatenate to the form of "This is a new line.". We then writelines the tuple to the bottom of the text file which gives the concatenated string.

Finally, don't forget to close any streams to save changes and avoid conflicts...

  1. readFile.close();
  2. writeFile.close();

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.