how to read from files in python code example
Example 1: python make txt file
file = open("text.txt", "w")
file.write("Your text goes here")
file.close()
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
Example 2: python open and reacd file
with open('yourfile.txt','r') as f:
lines = f.readlines()
f.close()
Example 3: 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 4: how to write a python variable to a file
#use pickle
import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()
#and to read it again
file = open('dump.txt', 'r')
dict = pickle.load(file)