File I:O

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

File I/O

OPEN:
“open” – It opens files programmatically, writing or reading.
- file = open(“names.txt”, “w”) – opening names.txt file and “w”riting to the program
- file.write(variable)
- file.close() – You always have to close the program if using open
o The problem with writing and not appending is that you’re creating the file and
recreating the file every time.
o If you change “w” --> “a” you will append what you’re trying to do to the code
 When appending the \n that is always in print is not there
WITH
- “with” automatically opens and closes the file
o with open(“names.txt”, “a”) as file:
 file.write(variable)

o reading - if you use “r” instead of “a” you will read the file (You don’t need to use
“r”, because it’s the default of with)

 lines = file.readlines()
 this will read all the lines
 for line in lines:
 print(line)
o sorti cng – to sort without having to create a list of ordered names
 with open(“names.txt”) as file:
 for line in sorted(file, reverse=False):
o print(“hello”, file)

CSV
- “Comma separated value.”
o with open(“students.csv”) as file:
 for line in file:
 row = line.rstrip().split(“,”)
 print(f”{row[0]} is in {row[1]})

You might also like