File operations:
- File reading
- File writing
- appending the content
File Reading:
with open('Logs.txt', 'r') as file:
open is python built in function used to open file. First arguments refers the file name and second argument is mode of reading.
with statement is for automatic closing of file. This will prevent memory leaks, providing a better resource manageement
as file as keyword assigns the opened file object to variable file
with open('logs.txt', 'r')as file:
# print(file, type(file))
content = file.readlines()
print(content, type(content)) # this content is a list. Elements are each line in file
for line in content:
print(line, end='') # end='' is defined to avoid \n as list iteration ends already with \n
#print(line.strip())
Output:
['This is the file used to store logs\n', 'Created on 12.08.2024\n', 'Author Suresh Sundararaju\n'] <class 'list'>
This is the file used to store logs
Created on 12.08.2024
Author Suresh Sundararaju
- file.readlines() will give the file content as list
file.readline() will give the first line as string
Iterating the list, each line can be retrieved as string
Iterating the later, each str can be retrieved as character
Here when iterating the list via for loop, the return ends with newline. when printing with print statment, another new line comes. To avoid that strip() or end='' is used
File writing:
with open('notes.txt','w') as file:
This is similar to file reading. the only syntax difference is mode is given as 'w'. Here notes.txt file will be created.
Further to write the content, we can use file.write('Content')
In write mode, a file is created each time and the content within that block is overwritten
# Write in file
with open('notes.txt', 'w') as file:
i=file.write('1. fILE CREATED\n')
i=file.write('2. fILE updated\n')
Appending in file:
with open('notes.txt', 'a') as file:
For appending, mode='a' is to be used with file.write(str) or file.writelines(list). Here in the existing file, the content will be updated at the end.
#Append file
with open('notes.txt', 'a') as file:
file.write('Content appended\n')
#Read all the lines and store in list
with open('notes.txt', 'r') as file:
appendcontent = file.readlines()
print(appendcontent)
Output:
['1. fILE CREATED\n', '2. fILE updated\n', 'Content appended\n']
Notes:
- There is some other modes available 'r+','w+','a+'
- exception can be added
Top comments (2)
Suresh S,
thank you for your article.
I like how it keeps things simple and structured.
I also tested the code with Colab and it works wonderfully as described.
There are some minor typos that I want to mention here:
"file.readlines ()" -> "file.readlines()"
"Withe write mode, everytime file will be created and content will be overwriten within that block"
Suggestion:
"In write mode, a file is created each time and the content within that block is overwritten"
Thank you Akin. I have updated the post as per the comments