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()