files
files
files
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exist, or else you will get an error.
Asume we have the following file, located in the same folder as Python:
demofile.txt
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
By default the read() method returns the whole text, but you can also specify how many character you want to
return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline() method:
Example
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
f = open("demofile.txt", "r")
for x in f:
print(x)
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
Example
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exist before you try to delete it:
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
Example
import os
os.rmdir("myfolder")
In this article, you'll learn about Python file operations. More specifically, opening a file, reading from it, writing
into it, closing it and various file methods you should be aware of.
What is a file?
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile
memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for
future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so
that resources that are tied with the file are freed.
Open a file
Read or write (perform operation)
Close the file
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append
'a' to the file. We also specify if we want to open the file in text mode or binary mode. The default is reading in text
mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like
image or exe files.
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not
exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already
exists, the operation fails.
'a' Open for appending at the end of the file without
truncating it. Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
Unlike other languages, the character 'a' does not imply the number 97 until it is encoded using ASCII (or other
equivalent encodings). Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in
Linux. So, we must not also rely on the default encoding or else our code will behave differently in different
platforms. Hence, when working with files in text mode, it is highly recommended to specify the encoding type.
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close the file.
f = open("test.txt",encoding = 'utf-8')
f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the
code exits without closing the file.
try:
f = open("test.txt",encoding = 'utf-8')
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing program flow to
stop.
The best way to do this is using the with statement. This ensures that the file is closed when the block inside with is
exited.
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode. We
need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method returns the number
of characters written to the file.
f.write("This file\n\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is overwritten.
There are various methods available for this purpose. We can use the read(size) method to read in size number of
data. If size parameter is not specified, it reads and returns up to the end of the file.
'This'
' is '
''
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get empty string on
further reading.
We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our
current position (in number of bytes).
56
This file
We can read a file line-by-line using a for loop. This is both efficient and fast.
...
This is my first file
This file
Moreover, the print() end parameter to avoid two newlines when printing.
Alternately, we can use readline() method to read individual lines of a file. This method reads a file till the newline,
including the newline character.
>>> f.readline()
>>> f.readline()
'This file\n'
>>> f.readline()
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading method return
empty values when end of file (EOF) is reached.
>>> f.readlines()
There are various methods available with the file object. Some of them have been used in above examples. Here is
the complete list of methods in text mode with a brief description.
Method Description
close() Close an open file. It has no effect if the file is already
closed.
detach() Separate the underlying binary buffer from the
TextIOBase and return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n) Read atmost n characters form the file. Reads till end of
file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Read and return one line from the file. Reads in at most
n bytes if specified.
readlines(n=-1) Read and return a list of lines from the file. Reads in at
most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to
from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resize the file stream to size bytes. If size is not
specified, resize to current location.
writable() Returns True if the file stream can be written to.
write(s) Write string s to the file and return the number of
characters written.
writelines(lines) Write a list of lines to the file