0% found this document useful (0 votes)
41 views15 pages

File IO

The document discusses various methods for reading and writing files in Python. It explains how to open a file, read the entire file as a string, read line by line, read character by character, read word by word, read numbers, write to a file, and append to a file. Key functions covered include open(), read(), readline(), write(), split(), and int() for file input/output operations in Python.

Uploaded by

almulla7x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views15 pages

File IO

The document discusses various methods for reading and writing files in Python. It explains how to open a file, read the entire file as a string, read line by line, read character by character, read word by word, read numbers, write to a file, and append to a file. Key functions covered include open(), read(), readline(), write(), split(), and int() for file input/output operations in Python.

Uploaded by

almulla7x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

File I/O

open
• Open is a function that reads a file and returns a file Object

Open(file,mode,…)

Open(‘file1.txt’) #is the same as


Open(‘file1.txt’,’r’) #open file to read from

a = open(‘file1.txt’,’r’) # a is a file object


read & readline
read([size])
Read and return at most size characters from the stream as a single str.
If size is None, reads until EOF.

readline([size])
Read until newline or EOF and return a single str. If the stream is
already at EOF, an empty string is returned.
If size is specified, at most size characters will be read.
Return entire file as a string
#get entire file in one shot
f = open("read1.py",’r')
data = f.read() #returns a string of entire file with \n for each line
print("length: ",len(data))
print(data)
Read line by line from file
#get line by line
# open() returns a file object to read2.py for reading text
f = open("read2.py",'r')
counter = 1
for line in f: #loop over the file object and get line by line

print(counter , line)
counter += 1
‘’’note the output when run. Each line has a space?
why? \n in the line and the print function prints then new
line ‘’’
Read line by line from file, another way
‘’’alternative way; note there is no blank lines between each line like in
previous code ‘’’
f = open("read2.py",'r')
#returns a string of entire file split into lines with \n
listOfLines = f.read().split('\n')
print(listOfLines)
counter = 1
‘’’loop over the list of lines and get line by line; Note each line does
not end with \n ‘’’

for line in listOfLines:


print(counter,line)
counter += 1
Yet another line by line using while loop
#get line by line
f = open("read3.py",'r')
# readline for line with 4 blanks returns 4blanks followed by \n
currentLine = f.readline()
counter=0
#readline for emptyLine returns \n
while currentLine != ’': # readline when reaches eof returns '' empty string
counter += 1
print(counter , currentLine)
currentLine = f.readline()
print('Goodbye')
Getting char by char from input file
#read whole file then return char by char and print each char
file = open('ReadCharByChar2.py','r')
x = file.read()
for char in x:
print(char)
print('Goodbye')
Getting word by word
#get each word
f = open("read2.py",'r')
counter=1
for line in f: #loop over the file object and get line by line
for word in line.split(): #split line into list of words
print(counter , word)
counter += 1
Reading numbers
#get each number
f = open("numbers.txt",'r')
sum = 0
for line in f: #loop over the file object and get line by line
for num in line.split(): #split line into a list words/numbers
print(num)
sum += int(num) #type cast string to int
print(sum)

‘’’ Data file


1 3
4 5 6
2 1 ‘’’
Printing to a file, write
objectOutFile = open('a1.txt','w') # create new else delete then write
for x in range(10):
print(x)
objectOutFile.write(str(x)+'\n') #write only string; no numbers
objectOutFile.close()
Printing to a file, append
objectOutFile = open('a1.txt',’a') #add to file
for x in range(10):
print(x)
objectOutFile.write(str(x)+'\n') #write only string; no numbers
objectOutFile.close()
'''
#get entire file in one shot
f=open('data1.txt','r') #returns a _io.TextIOWrapper
data = f.read() #returns a string of entire file
print(data)

#read char by char,


f=open('homework2v2.py','r')
string=f.read() #returns the whole file as a string
for char in string:
print(char)

#read line by line, method2


f=open('data1.txt','r')
line = f.readline()
while line != '':
print(line)
line = f.readline()

#read word by word


f=open('homework2v2.py','r') #returns a _io.TextIOWrapper
print(type(f))
for line in f:
for word in line.split():
print(word)

#read number by number


f=open('numbers.txt','r') #returns a _io.TextIOWrapper
print(type(f))
sumTotal=0
for line in f:
sumRow=0
for number in line.split():
print(number,end=' ')
sumTotal += int(number)
sumRow += int(number)
print()
print('Sum Row: ',sumRow)
print('sum=',sumTotal)
'''
objectOutFile = open('a1.txt','w') # create new else delete then write
for x in range(10):
print(x)
objectOutFile.write(str(x)+'\n') #write only string; no numbers
objectOutFile.close()

objectOutFile = open('a1.txt','a') # create new else add to end then write


for x in range(10):
print(x)
objectOutFile.write(str(x)+'\n') #write only string; no numbers
objectOutFile.close()
#get each number
f = open("numbers.txt",'r')
sum=0
for line in f: #loop over the file object and get line by line
sumPerLine = 0
for num in line.split(): #split line into a list words/numbers
#print(num)
sumPerLine += int(num) #type cast string to int
sum += int(num)
print('Sum per line',sumPerLine)
print('Total sum',sum)

You might also like