I/O Flashcards
Create a txt file called “output” and store it in the variable “file”, then write “Hello” to that file
with open(‘output.txt’, ‘w’) as file”:
file.write(‘Hello’)
with open(‘output.txt’, ‘w’) as file:
What does the “w” do in the method above
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.
write()
writelines()
With regards to saving data to a file, what’s the difference between the above two
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”])
Read a txt file called “output” (so it will be ready for editing) and store it in the variable “content”
with open(‘output.txt’, ‘r’) as file:
content = file.read()