read data from a file python code example
Example 1: python read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
Example 2: read file python
document = 'document.txt'
file = open(document, 'r')
# 'r' can be replaced with:
# 'w' to write
# 'a' to append (add to the end)
# 'w+' makes a new file if one does not already exist of that name
# 'a+' is the same as 'w+' but it appends if the file does exist
##go to beginning of document
file.seek(0)
##print all lines in document, except empty lines:
for i in file:
k = i.strip()
print k
##close the file after you are done
file.close()
##this can temporarily open a file:
with open(document) as ur:
for i in ur:
k = i.strip()
print k
Example 3: python read file
txt = open('FILENAME.txt')
txtread = txt.read()
print(txtread)
print(txt.read())
Example 4: how to read a file in python
# when you want to read the file from terminal in python use
import sys
f = open(sys.argv[1])
line=f.readline()