PR1 – Preparation for Week 8 – Writing a file

uthor:Carlos Santos
Learning Line:Programming
Course:PR1: Introduction to Programming
Week:8
Competencies:Students will be able to effectively define and use variables, programming flow control.
BoKS:­ 3bK2, The student understands the principles of data related software like Python, R, Scala and/or Java and knows how to write (basic) scripts.
Learning Goals:Able write text files

Writing a Text File

Writing a file is very similar to reading a file, you open the file, you write on it, and then you close the file.

f = open("testfile.txt","w")
f.write("hi")
f.close() 

Open actually has many operational modes.

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)

It is perfectly normal to do something link open(“testfile.txt”,”rw+t”), meaning please open a text(t) file for read(r) and write(w) operations, and do not delete the content (+) we will be updating it.

Writing Methods

Once you’ve opened up a file, you’ll want to write its content. You can using different methods.

MethodWhat It Does
.write(string)This writes the string to the file.
.writelines(seq)This writes the sequence to the file. No line endings are appended to each sequence item. It’s up to you to add the appropriate line ending(s).