1.2 Working with text files
The post explains how to create and work with text files in python.
- Working with text file in python
- Using .read() and .seek()
- Using .readlines()
- Writing a file - Understanding the mode
- Appending a file
- Aliases and context managers
- Iterating through a file
%%writefile test.txt ( Use this magic command before the text)
Hello, this is a new file create using python ide.
This the second line of the file.
Give the location of the present working directory
pwd()
Opening the file
myfile = open("test.txt")
myfile
This is the location in the memory which hold the file.
myfile.read()
myfile.read()
The second time the function it called it does not give any output since the cursor has reached the end of the document. There is nothing more read. Hence we need to reset the cursor to the start.
Resetting the cursor
myfile.seek(0)
myfile.read()
readlines() help to read the file line by line. Note: All the data is helded in the memory, hence large files will need to handled carefully.
myfile.seek(0)
myfile.readlines()
myfile.close()
While opening the file, we can open it with different modes
- 'r' default to read the file
- 'w+' read and write the file.(Overwrites the existing file)
- 'wb+' read and write as binary (used in case of pdf)
myfile = open("test.txt", mode= 'w+')
myfile.write("This is an additional file")
myfile.seek(0)
myfile.readlines()
Hence the existing data is deleted and the new data is overwrite.
myfile.close()
Passing the argument 'a'
opens the file and puts the pointer at the end, so anything written is appended.
myfile = open("test.txt", 'a+')
myfile.write("\nAppending a new line to the existing line")
myfile.seek(0)
print(myfile.read())
myfile.close()
You can assign temporary variable names as aliases, and manage the opening and closing of files automatically using a context manager:
with open('test.txt','r') as txt:
first_line = txt.readlines()[0]
print(first_line)
By using this method, the file is opened, read and closed by context mananger automatically after doing the specified operation.
first_line
txt.read()
Hence the extract line remain in the object but the file is closed by the context manager.
with open('test.txt', 'r') as txt:
for line in txt:
print(line , end='$$$$')