Python File I/O
Published in
2 min readOct 6, 2023
Unlock the file input and output world in Python with these handy snippets. Learn how to read the entire content of a file or go line by line. You can also write, append, or perform both read and write operations. Additionally, discover how to create a translator that converts text to zh-TW (traditional Chinese) and writes it in a new file, with each line limited to 50 characters for easy readability. Explore the endless possibilities of file manipulation in Python!
Read
- Read the entire file.
with open('files/file.txt', mode='r') as my_file:
print(my_file.read())
- Read line by line.
with open('files/file.txt', mode='r') as my_file:
print(my_file.readline())
Write
with open('new.txt', mode='w') as my_file:
text = my_file.write('this is a new file')
Append
with open('test.txt', mode='a') as my_file:
text = my_file.write(':)')
Read and Write
with open('test.txt', mode='r+') as my_file:
text = my_file.write('hey it\'s me.')
Translator
- Translate the word to zh-TW and write in a new file.
- Move to a new line when writing 50 characters in one line.
from translate import Translator
# Create a Translator instance
translator = Translator(to_lang="zh-TW")
try:
with open('./untranslated_words.txt', mode='r') as my_file:
with open('./translated-zh-tw.txt', mode='w') as my_file2:
while True:
# Read a chunk of text (up to 500 characters) from the file
chunk = my_file.read(500)
if not chunk:
# End of file reached
break
# Translate the chunk
translation = translator.translate(chunk)
# Write the translated text in lines of 50 characters each
for i in range(0, len(translation), 50):
line = translation[i:i + 50]
my_file2.write(line + '\n')
except FileNotFoundError as err:
print('File does not exist')
raise err