Files Flashcards
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)
- Open the file and associate the file with a file variable (file pointer)
- Command to read the info
- Comand to close the file
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)
- usually done within body of a loop
- each execution of the loop will read a line from file into a string
- the loop contiues to reasd lines from the files until the end is reached
- The loop wont execute if the file is empty
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>()
- Example:
~~~
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 = False
Writing 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()