how to display a list:
for r in range (0, ROW, 1):
for c in range (0, COL, 1):
print (aGrid[r][c], end="")
print()What do you need unorder to read info from a file? (3)
references to the file variable are
refereces to the physical file
format for file variable:
<file variable> = open(filename, mode)
ex”
~~~
inputFile = open(“data.txt”, “r”)
~~~
Reading info from files (4)
The loop body to read files:
for (variables to store in a string) in (name of file variable):
<Do>
~~~
for line in inputFile:
print(line)
~~~
</Do>
Although your file closes automatically when program ends you should still manually close it…. how do you do that?
<name of file variable>.<close>()
inputFile.close()
~~~
Code for how file is imputted+ empty checking
def file_read():
fileOk = False
old_world = []
while fileOk == False:
filename = input("Enter the name of the input file: ")
try:
inputfile = open(filename, 'r')
aLine = inputfile.readline()
if aLine == '':
print("%s is an empty file" % filename) # Displays message if file is empty
else:
fileOk = True
while(aLine != ""):
temp_row = []
old_world.append(temp_row)
for ch in aLine:
if ch != "\n":
temp_row.append(ch)
aLine = inputfile.readline()
inputfile.close()
except IOError:
print("Problem reading from file %s" % filename) #Display message if file cannot be read
fileOk = FalseWriting to a file example:
inputfilename = input)…
outputfilename = output)….
inputfile = open(inputfilename, “r”)
output = open(outputfilenae, “w”)
gpa = …
for line in input file:
if……
temp = str(gpa)
outputfile.write(temp)
inputfile.closed()
outputfile.closed()