Files Flashcards

1
Q

how to display a list:

A
for r in range (0, ROW, 1):
    for c in range (0, COL, 1):
        print (aGrid[r][c], end="")
print()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What do you need unorder to read info from a file? (3)

A
  1. Open the file and associate the file with a file variable (file pointer)
  2. Command to read the info
  3. Comand to close the file
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

references to the file variable are

A

refereces to the physical file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

format for file variable:

A
<file variable> = open(filename, mode)

ex”
~~~
inputFile = open(“data.txt”, “r”)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Reading info from files (4)

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The loop body to read files:

A

for (variables to store in a string) in (name of file variable):

<Do>
~~~
for line in inputFile:
print(line)
~~~
</Do>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Although your file closes automatically when program ends you should still manually close it…. how do you do that?

A
<name of file variable>.<close>()
  • Example:
    ~~~
    inputFile.close()
    ~~~
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Code for how file is imputted+ empty checking

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Writing to a file example:

A

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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly