Popular Posts

Tuesday, September 8, 2020

Python Beginner: Reading Files

 Hello, Developer!


Today, we will learn "Reading Files" feature in order to read external files. We use files everyday because we save data as file type in a computer storage for accessing  as long as possible. There are many types of files but in this course, we will exercise to read a saved txt file.


Reading File Function Form

File_object = open("External file name(i.e. reading_test.txt)", "mode(i.e. r(reading), w(writing), a(appending), r+(reading & writing"))) # Opening an external file for access purpose(read, write, append and read & write)

File_object.close


For reading file items, you can use "Read" & "Readlines" commands as below.


"Read" Command Form

File_object.read() # Read all items from the opened file


"Readlines" Command Form

File_object.readlines() # Read first one line data from the opened file

File_object.readlines()[n] # Read nth line items from the opened file


I showed all "Reading Files" exercise codes and executed result as following.

employee_file = open("employees.txt", "r")
print(employee_file.read())
employee_file.close()

employee_file = open("employees.txt", "r")
print(employee_file.readline())
print(employee_file.readline())
print(employee_file.readline())
employee_file.close()

employee_file = open("employees.txt", "r")
print(employee_file.readlines()[1])
employee_file.close()

employee_file = open("employees.txt", "r")
for employee in employee_file.readlines():
print(employee)
employee_file.close()

 

Can you see the same result on your PC? Congratulations! Great job! Now you can open the text file and read data from the opened file.


See you on the next post, developer! 😊

1 comment:

  1. Casino at Foxwoods Resort & Casino | MapyRO
    Search for 충청남도 출장마사지 Casino at Foxwoods Resort & Casino in New York City, United States of America 이천 출장안마 on MapyRO. Find your way around 순천 출장샵 the casino, find 광주 출장마사지 where everything 부산광역 출장샵 is

    ReplyDelete

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...