Skip to main content

How to Read and Write To/From Files in Python


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();

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.