Python Tutorial : How to Open Files with Python

Here I will be opening a file that has been saved on a computer. For this example, the file is a .txt text file that contains a random list of words. In the first block of code, the file is saved in the “C:” drive and then selected from the “Desktop” so make sure to change that portion of code to the proper path of the file you are trying to open.

To open a file use .read()

 file = open("C:/Users/Comp/Desktop/TextFile.txt", "r")
 print(file .read())

Use readline() to select a certain line form the file.

 file = open("C:/Users/Comp/Desktop/TextFile.txt", "r")

#Select exact line in file
#Here the Second Line is chosen 
print(file .readline(2))

Loop through a file’s content

 file = open("C:/Users/Comp/Desktop/TextFile.txt", "r")

#Loop line by line through file
for x in file :
  print(x)

Use .close() to close the selected file

 file = open("C:/Users/Comp/Desktop/TextFile.txt", "r")
 print(file .read())

#Closing the file 
file.close()

Click here for more Python Tutorials

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s