13.2. Working with Text files#
Text files:
Plain text
XML
JSON
Source code
When you open a file,3 modes are there:
Read mode,’r’
If file allready exists,python will read it
If file doesn’t exists,python will give error
so wrap it in try block
Write mode,’w’
If file allready exists,python will overwrite it
If file doesn’t exists,python will create it
Append mode,’a’
If file allready exists,python will append text in end
If file doesn’t exists,python will create it
13.2.1. Read the file#
try:
with open('sahil.txt','r') as f:
text=f.read()
except FileNotFoundError:
text=none
print(text)
A
B
C
D
E
F
13.2.2. Write to file#
l=['A','B','C']
with open('sahil.txt','w') as f:
for i in l:
f.write(i)
13.2.2.1. Check the file#
with open('sahil.txt') as f:
text=f.read()
print(text) ### previous text got overwritten
# also,no line separators by default
ABC
13.2.2.2. Adding the new line manually#
l=['A','B','C']
with open('sahil.txt','w') as f:
for i in l:
f.write(i)
f.write('\n')
13.2.2.3. Check the file#
with open('sahil.txt') as f:
text=f.read()
print(text)
A
B
C
13.2.3. Append to File#
l=['D','E','F']
with open('sahil.txt','a') as f:
for i in l:
f.write(i)
f.write('\n')
13.2.4. Check the file#
with open('sahil.txt','r') as f:
text=f.read()
print(text)
A
B
C
D
E
F