read()
file = open('hello.txt')
txt = file.read()
print(txt)
hello there! this is a plain text file with 3 lines
readlines()
file = open('hello.txt')
lines = file.readlines()
print(lines)
['hello there!\n', 'this is a plain text file\n', 'with 3 lines']
# os is a Python module that makes it possible to interact with the operating system
# we will use it to list all the files that sit in a specific folder
import os
# This is where our plain text files are that we want to open
path = './plain-text-files/'
# This is the list that we want to fill with files
files = []
# os.listdir() returns a list containing the names of the files in this folder
for filename in os.listdir(path):
# os.path.join() glues the path + filename together
file_path = os.path.join(path, filename)
print('---')
print('filename :', filename)
print('file_path :', file_path)
# os.path.isfile() checks if this is a "regular file"
if os.path.isfile(file_path) == True:
# if that is the case (is True)
# then we add the file_path to the list called "files"
# we use .append() for this, which is a Python way to add items to lists
files.append(file_path)
print('file_path added to list : YES')
else:
print('file_path added to list : NO')
--- filename : .ipynb_checkpoints file_path : ./plain-text-files/.ipynb_checkpoints file_path added to list : NO --- filename : hello-xpub.txt file_path : ./plain-text-files/hello-xpub.txt file_path added to list : YES --- filename : hello-world.txt file_path : ./plain-text-files/hello-world.txt file_path added to list : YES
files
['./test/hello-xpub.txt', './test/hello-world.txt']
read()
for file_path in files:
print('---')
print('file_path :', file_path)
file = open(file_path, 'r') # 'r' stands for 'reading', it means that we only open this file for reading its content
print('file :', file)
# Open the file and read() its content as a single string
txt = file.read()
print('txt :', txt)
--- file_path : ./plain-text-files/hello-xpub.txt file : <_io.TextIOWrapper name='./plain-text-files/hello-xpub.txt' mode='r' encoding='UTF-8'> txt : hello XPUB ? ? ? --- file_path : ./plain-text-files/hello-world.txt file : <_io.TextIOWrapper name='./plain-text-files/hello-world.txt' mode='r' encoding='UTF-8'> txt : hello world! ! ! !
readlines()
for file_path in files:
print('---')
print('file_path :', file_path)
file = open(file_path, 'r') # 'r' stands for 'reading', it means that we only open this file for reading its content
print('file :', file)
# Open the file and readlines() its content as a list of lines
lines = file.readlines()
print('lines :', lines)
--- file_path : ./plain-text-files/hello-xpub.txt file : <_io.TextIOWrapper name='./plain-text-files/hello-xpub.txt' mode='r' encoding='UTF-8'> lines : ['hello XPUB\n', '?\n', '?\n', '?'] --- file_path : ./plain-text-files/hello-world.txt file : <_io.TextIOWrapper name='./plain-text-files/hello-world.txt' mode='r' encoding='UTF-8'> lines : ['hello world!\n', '!\n', '!\n', '!\n']