Python3 File Management
This page shows how to work with text files using Python3 code. Following is a sample txt file we will be using. Lets called it stocks.txt
bce.to
hnd.to
mtl.to
Reading from File
You can use read(), readline(), or readlines() function to read from a file. This example uses read()
stocks = open("data/stocks.txt","r")
stocks.read()
stocks.close()
output:
'bce.to\nhnd.to\nmtl.to'
Using readline():
stocks = open("data/stocks.txt","r")
stocks.readline()
stocks.readline()
stocks.close()
output:
bce.to
hnd.to
Note that each readline() will print the next row in the file.
Using readlines(): Note the plural readlines as opposed to readline.
stocks = open("data/stocks.txt","r")
stocks.readlines()
stocks.close()
output:
['bce.to\n', 'hnd.to\n', 'mtl.to']
readlines() outputs each row as a list element
Easy way to remove newlines
stocks = open("data/stocks.txt","r")
for stocksymbol in stocks.read().splitlines():
print(stocksymbol)
stocks.close()
output:
bce.to
hnd.to
mtl.to
Write to File
fh = open("data/stocks.txt", "w")
newstock = 'ta.to'
fh.write(newstock)
fh.close()
After you run the code, stocks.txt will contain
ta.to
Your code overwrote the existing contents of the file. To append the text rather than overwriting, use the "a" option:
fh = open("data/stocks.txt", "w")
newstock = 'ta.to'
fh.write(newstock)
fh.close()
After you run the code, stocks.txt will contain
bce.to
hnd.to
mtl.to
ta.to