I/O Flashcards

1
Q

Create a txt file called “output” and store it in the variable “file”, then write “Hello” to that file

A

with open(‘output.txt’, ‘w’) as file”:
file.write(‘Hello’)

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

with open(‘output.txt’, ‘w’) as file:

What does the “w” do in the method above

A

This parameter space is called the mode.

Specifically “w” stands for write mode. It means:
1) If the file exists, empty it.
2) If the file doesn’t exist, create a new one.

You can then write new content into the file.

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

write()

writelines()

With regards to saving data to a file, what’s the difference between the above two

A

Write() - Takes a String and writes it

E.g., file.write(“Hello\n”)

Writelines() - Takes a List and writes it (no auto-newline)

E.g., file.writelines([“Hello\n”, “World\n”])

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

Read a txt file called “output” (so it will be ready for editing) and store it in the variable “content”

A

with open(‘output.txt’, ‘r’) as file:
content = file.read()

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