Read/Write Flashcards
Reading input from console
prompt = "Hey, what's up? " user_input = input(prompt) print("You said: " + user_input)
Reading text file
The mode argument is optional and the default value is r. In this notebo
Read file example
# 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()
~~~
Right way to read file
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
Writing files
# 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
Writing to file using loop
# 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
Appending data to exisitng file
# 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