Source: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
In Python you can use libraries to access other file types like text, excel, CSV etc. The first step is to open a stream to the file you wish to access using the open command. There are three types of modes that you can use:
‘r’ – Read mode which is used when the file is only being read
‘w’ – Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end of the file; that is new information is automatically amended to the end
‘r+’ – Special read and write mode, which is used to handle both actions when working with a file
file = open('name of file','mode')
#open a text file and pull lines into a list
file = open('DB','r')
#read file contents into a list based on a new line
alist = file.read().splitlines()
#print the list in the python console
print(alist)
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
#Summing values in a text file
file = open('data.txt','r')
numbers = file.read().splitlines()
print(numbers)
total = 0
for i in numbers:
total = total + int(i)
print(total)
import csv
with open("data1.csv") as myfile:
csv_records = csv.reader(myfile)
list1 = []
list2 = []
for row in csv_records:
list1.append(int(row[0]))
list2.append(int(row[1]))
print(list1)
print(list2)