How to Read and Write To/From Files in Python
Submitted by Yorkiebar on Monday, March 10, 2014 - 06:45.
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...
Or to open for writing purposes, we can use...
Reading:
We can output the next line of a text file using .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...
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...
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...
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...
We could also use writelines to append a list of strings to the bottom of the file...
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...
- readFile = open("leaderboard.txt", "r");
- writeFile = open("leaderboard.txt", "w");
- print(readFile.readline());
- readFile.close();
- readFile = open("leaderboard.txt", "r");
- allLines = readFile.readlines();
- for line in allLines:
- print(line);
- print(readFile.read(2));
- print(readFile.read(16));
- writeFile.write("Hey there!");
- myLines = ("This ", "is ", "a ", "new ", "line.");
- writeFile.writelines(myLines);
- readFile.close();
- writeFile.close();
Add new comment
- 74 views