Software DD (Implementation: File Handling) *Need to add Mr Ammann's examples Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Python File Access Modes

A

Some other Python File Access Modes
* r - Open for reading (this is the default)
* w - Open for writing, truncating the file first
* a - Open for writing, appending to the end of the file if it exists

From RGC Aberdeen website

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

File Access Modes

A

When a file is opened you have to specify how it should be opened. This is what type of access you will be using. When opening a file we can set the following modes:

  • Reading (this is the default and opens the file in a read only mode)
  • Writing (will usually overwrite the file)
  • Appending (will add to the end of the existing contents)

From RGC Aberdeen website

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

File Reading (Pseudocode)

A

Assuming that the file exists in the same folder as the Python Program the pseudocode below shows opening a file for reading and reading all of the contents into a variable called filecontents.

OPEN FILE(SAMPLEFILE.txt) FOR READING
filecontents = FILE.READ
CLOSE FILE

From RGC Aberdeen website

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

File Reading (Python)

A

The code below would open the file for reading. Again assuming that the file sampleFile.txt is in the same folder. When the file has been read into the variable called filecontents
Once the with loop ends the file is closed. Remember to put Close File in pseudocode.

with open(“sampleFile.txt”) as readfile:
filecontents = readfile.read()
print(filecontents)

From RGC Aberdeen website

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

File Writing (Pseudocode)

A

OPEN FILE(“newfile.txt” for WRITING)
WRITE Python is great fun” TO FILE
WRITE “This text will be on another line” TO FILE
CLOSE FILE

From RGC Aberdeen website

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

File Writing (Python)

A

with open(“newfile.txt”,”w”) as writefile:
writefile.write(“Python is great fun” + ‘\n’)
writefile.write(“This text will be on another line”)

From RGC Aberdeen website

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