Popular Posts

Tuesday, September 8, 2020

Python Beginner: Writing to Files

 Hello, Python developer!


Today, we will learn the "Writing to Files" function. We will write and append data in the external text file.

The "Append" function will preserve current file data and add data at the end of the file. This function is useful to add updated data to the file. 


Append Function Form

File_object = open("External file name", "a") # Preserve file data and add data at the end of file data

File_object.write("Adding data")

File_object.close


The  "Write" function will ignore current file data so remove all data in the file and write designated data in the file.


Write Function Form

File_object = open("External file name", "w") # Remove all file data and add data to the file from starting

File_object.write("Adding data")

File_object.close


I showed all "Append" and "Write" mode exercise codes and executed result as following.

employee_file = open("employees.txt", "a")
employee_file.write("Toby - Human Resources ")
employee_file.close()

employee_file = open("employees.txt", "a")
employee_file.write("\nToby - Human Resources ")
employee_file.close()

employee_file = open("employees.txt", "w")
employee_file.write("Kelly - Customer Service")
employee_file.close()

employee_file = open("employees001.txt", "w")
employee_file.write("Kelly - Customer Service")
employee_file.close()

employee_file = open("index.html", "w")
employee_file.write("<p>This is HTML</p>")
employee_file.close()

Can you see the same result on your PC? Great job! Now you can write data to the external files. 


Let's see you again in the next post, Developer! 😊

No comments:

Post a Comment

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...