Working with text files in Python
Python have open() function for working with files (read, write, modify). It open file with specified permission and returns as object. The open() function take two arguments: filename and file opening mode (both strings). Filename maybe absolute or relative. When you set only filename, Python try to open file in the same directory, which script. File open mode may be single or combination of some. File permission modes in Python:
r - read file without making any changes.
w - write in file. If file exist data will be overrided.
a - append data in bottom of file.
x - create empty file.
t - text mode. May be used for read (rt) or write (wt).
b - binary mode. May be used for read (rb) or write (wb).
+ - open file for updating.
Read data from existing and not empty file:
Write a single line in newly created file. If file exists and not empty - data will be overrided:
If you have a large list of data, you can write it using a for loop:
Check out file for empty lines. How it works? First line of code opens source and destination files. Second line start for loop. Third line check each iteration of loop, is line equal to space. Fourth line write not empty string in destination file.
r - read file without making any changes.
w - write in file. If file exist data will be overrided.
a - append data in bottom of file.
x - create empty file.
t - text mode. May be used for read (rt) or write (wt).
b - binary mode. May be used for read (rb) or write (wb).
+ - open file for updating.
Read data from existing and not empty file:
with open('file.txt', 'r') as file:
print(file.read())
Write a single line in newly created file. If file exists and not empty - data will be overrided:
with open('file.txt', 'w') as f:
f.write('Create file in write mode')
If you have a large list of data, you can write it using a for loop:
my_list = [
'apple', 'banana', 'orange'
]
with open('file.txt', 'w') as f:
for line in my_list:
f.write(f'{line}\n')
Check out file for empty lines. How it works? First line of code opens source and destination files. Second line start for loop. Third line check each iteration of loop, is line equal to space. Fourth line write not empty string in destination file.
with open('input_file.txt', 'r') as input_file, open('output_file.txt', 'w') as output_file:
for line in input_file:
if not line.isspace():
output_file.write(line)
Support me on Patreon
#file #python #read #text #write