xxxxxxxxxx
with open ("data.txt", "r") as myfile:
data = myfile.read().splitlines()
xxxxxxxxxx
# read and print all contents of a file
with open('data.txt', 'r') as f:
contents = f.read()
print(contents)
# loop through file line by line removing newlines
with open('data.txt', 'r') as f:
for line in f:
print(line.rstrip())
# read first 14 bytes of file
with open('data.txt', 'r') as f:
print(f.read(14))
print(f"The current file position is {f.tell()}")
# move to beginning of file
f.seek(0, 0)
# print 30 bytes from position
print(f.read(30))
xxxxxxxxxx
# where f is the file alias
with open(r"path\to\file.txt", encoding='UTF8') as f:
contents = f.read()
print(contents)
xxxxxxxxxx
file = '/home/text/chapter001.txt'
f=open(file,'r')
data = f.read()
print('data =',data)
xxxxxxxxxx
# Way 1 : data in raw text
with open('filename.txt', 'r') as file:
print(file.readline())
# Way 2 : data similar to dataframe format
data = np.genfromtxt('filename.csv', delimiter=',', names=True, dtype=None)
# Way 3 : not recommended
data = np.loadtxt('filename.txt', delimiter= ',', skiprows=1, usecols=[0,2], dtype=str)
xxxxxxxxxx
with open('readme.txt') as f:
lines = f.readlines()
Code language: Python (python)