Python File I/O
In this article, I will show you some points of Python File I/O subject.
Lately, one of my colleague give me a project, which will tells us the project’s average compile times. With that new project, we will able to see which project is taking much time and which isn’t. So, we can reduce the compile time and calculate the best effort for selecting and working on one of them.(We have lots of projects in one solution)
I took the job and started working on it. I decided to write python script.
Anyway, I would like to give you some python file I/O examples with help of knowladge which I gain while writing that script.
First of all, python has very generous and simple language, like English. Some says, if you know English, then you can write python 🙂
In this article, we will see basic operations of Python File I/O..
Anyway, we can create a file like this below code block:
myFile = open("orcunland.txt",'a+', newline="\r\n")
As you know, “a+” Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Now, myFile is ready to take inputs and write them to it’s lines.
For that job, I need a function, which is simple as above one.
myFile.write("You shall not pass! \r\n")
And it’s done! Now myFile has it’s very first line. Instead, what it need is, lots of lines, which force us to use loops for that. No problem with that. See below:
for i in range(1,10):
myFile.write(i + "I will, demon!")
What will this code do? It will write my loops range and “I will, demon!” to myFile.
Anyway, after some inputs or outputs, we will close the file, because we don’t want to waste our additional memory used.
Like all the other functions, this is very easy too. See below:
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. A safer way is to use a try…finally block.
# encoding utf-8 means, we will encode our file according to utf-8 standarts,
# for some keyboard entries
myFile = open("orcunland.txt",encoding = 'utf-8')
# perform file operations
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing program flow to stop.
Reading From a File
To read the content of a file, we must open the file in reading mode. 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.
myFile = open("test.txt",'r',encoding = 'utf-8')
myFile.read(4) # read the first 4 data
myFile.read(4) # read the next 4 data
myFile.read() # read in the rest till end of file
myFile.read() # further reading returns empty sting
We can see, that 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).
myFile.tell() # get the current file position
myFile.seek(0) # bring file cursor to initial position
print(myFile.read()) # read the entire file
We can read a file line-by-line using a for loop. This is both efficient and fast.
for line in myFile:
print(line, end = '')
The lines in file itself has a newline character ‘\n’. Moreover,the print() function also appends a newline by default. Hence, we specify the 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.
'This is my first file\n'
'Goodmorning wishes you must have, my young padawan\n'
'Luke, I am your Father!\n'
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.
Now, I want to share with you a method list which you can use for all of your projects.
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.
Please, send me your feedbacks, so I can improve the quality of article.
['This is my first file\n', 'This file\n', 'contains three lines\n']