Before that lets see the File Modes in Python
File Modes in Python
|
|
Mode
|
Description
|
'r' |
Open a file for reading. (by default) |
'w' |
Open a file for writing. Creates a new file if it does not
exist or deleates 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 replacing it.
Creates a new file if it does not exist. |
't' |
Open in text mode. (by default) |
'b'
|
Open in binary mode. |
'+'
|
Open a file for updating (reading and writing) |
1. How to create a file
import os
file_name = 'ReddyInfoSoft.txt'
# Create File if it Does Not Exists
def create_file():
if not os.path.exists(file_name): # Check if file Exists or not
f = open(file_name, mode='w+')
f.close()
2. How to Write to File
# Write to the file
def write_2_file():
f = open(file_name, mode='w')
for i in range(9):
f.write('\nLine No:'+str(i))
f.close()
3. How to Append to File
def append_2_file():
f = open(file_name, mode='a+')
for i in range(9):
f.write('\nAppended Line No:'+str(i))
f.close()
4. How to read a file
# Read file (file can read only ones)
def read_file():
# reads entire file
f = open(file_name, mode='r')
print('Read All Lines\n')
data = f.read()
print(data)
f.close()
print('\nRead Line By Line\n')
f1 = open(file_name, mode='r')
lines = f1.readlines()
for line in lines:
print(line)
f1.close()
Combining All the parts will Look as shown Below.
import os
file_name = 'ReddyInfoSoft.txt'
# Create File if it Does Not Exists
def create_file():
if not os.path.exists(file_name): # Check if file Exists or not
f = open(file_name, mode='w+')
f.close()
# Write to the file
def write_2_file():
f = open(file_name, mode='w')
for i in range(9):
f.write('\nLine No:'+str(i))
f.close()
def append_2_file():
f = open(file_name, mode='a+')
for i in range(9):
f.write('\nAppended Line No:'+str(i))
f.close()
# Read file (file can read only ones)
def read_file():
# reads entire file
f = open(file_name, mode='r')
print('Read All Lines\n')
data = f.read()
print(data)
f.close()
print('\nRead Line By Line\n')
f1 = open(file_name, mode='r')
lines = f1.readlines()
for line in lines:
print(line)
f1.close()
if __name__ == "__main__":
create_file()
write_2_file()
append_2_file()
read_file()
No comments:
Post a Comment