11 - File IO
11 - File IO
The synchronous sessions are recorded (audiovisual recordings). The students are not required to keep their
cameras on during class.
The audiovisual recordings, presentations, readings and any other works offered as the course materials aim
to support remote and online learning. They are only for the personal use of the students. Further use of
course materials other than the personal and educational purposes as defined in this disclaimer, such as
making copies, reproductions, replications, submission and sharing on different platforms including the digital
ones or commercial usages are strictly prohibited and illegal.
The persons violating the above-mentioned prohibitions can be subject to the administrative, civil, and
criminal sanctions under the Law on Higher Education Nr. 2547, the By-Law on Disciplinary Matters of Higher
Education Students, the Law on Intellectual Property Nr. 5846, the Criminal Law Nr. 5237, the Law on
Obligations Nr. 6098, and any other relevant legislation.
The academic expressions, views, and discussions in the course materials including the audio-visual
recordings fall within the scope of the freedom of science and art.
‘w’ Open a file for writing. If the file already exists, erase its contents. If it doesn ot exist, create it.
‘a’ Open a file to be written to. All data written to the file will be appended to its end. If the file does not exist, create it.
▪ When opening files, you can specify an absolute path or a relative path
▪ Relative path is relative to the “current working directory (cwd)”
▪ To learn the current working directory:
▪ When file is in the same folder as the Python program (or nearby), using
relative paths makes things easy:
▪ If you need to, you should use relative paths in the homework (why?)
COMP 125 Programming with Python 10
Writing data into a file
for i in range(len(items)):
fvar.write(items[i]+"\t"+str(quantity[i])+"\n")
fvar.close()
Alternatives
▪ read: File object function that reads entire file contents into memory
▪ Contents returned as a string
▪ readlines: File object function that reads entire file contents
▪ Contents returned as a list of lines where each line is a string including ‘\n’
▪ What happens if the path of your output file does not exist?
25
COMP 125 Programming with Python
Example
▪ Write a function that creates an output
file with name number_list.txt and writes
the numbers 1 through 100 to that file.
31
Writing data into a .csv file
▪ Writing into the same column