Read/Write Flashcards

1
Q

Reading input from console

A
prompt = "Hey, what's up? "
user_input = input(prompt)
print("You said: " + user_input)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Reading text file

A

The mode argument is optional and the default value is r. In this notebo

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

Read file example

A
# Read the Example1.txt
example1 = "example1.txt"
file1 = open(example1, "r")

We can view the attributes of the file.
file.name
We can look at the mode
file.mode r - read mode

We can read the file and assign it to a variable :
~~~
FileContent = file1.read()
type(FileContent) type of FileContent is string
~~~

it’s important to close file if with is not used
~~~
file.close()
~~~

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

Right way to read file

A
with open(example1, "r") as file1:
    FileContent = file1.read()
    print(FileContent)

the with statment will make sure file is closed
we can check by looking at file.closed property

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

Writing files

A
# Create a new file Example2.txt for writing
with open('Example2.txt', 'w') as File1:
    File1.write("This is line A\n")
    File1.write("This is line B\n")

    # File1 is automatically closed when the 'with' block exits
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Writing to file using loop

A
# List of lines to write to the file
Lines = ["This is line 1", "This is line 2", "This is line 3"]

Create a new file Example3.txt for writing

with open('Example3.txt', 'w') as File2:
    for line in Lines:
        File2.write(line + "\n")
    
# File2 is automatically closed when the 'with' block exits
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Appending data to exisitng file

A
# Data to append to the existing file
new_data = "This is line C"

Open an existing file Example2.txt for appending

with open('Example2.txt', 'a') as File1:
    File1.write(new_data + "\n")

    # File1 is automatically closed when the 'with' block exits

‘a’ mode when opening a file to append new data to an existing file without overwriting its contents

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