Python – Read Lines from Text File

email me

Tested on a Mac, 10.12.6.

import os.path

textFile = "/Users/Shared/TextFile.txt"
doesFileExist=os.path.isfile(textFile)
if doesFileExist == True:
file = open(textFile,"r")
lines=file.read().splitlines()
global line1
global line2
line1 = lines[0]
line2 = lines[1]
file.close()

 

 

Notes

https://docs.python.org/3/

 

Mode Description
‘r’ This is the default mode. It Opens file for reading.
‘w’ This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
‘x’ Creates a new file. If file already exists, the operation fails.
‘a’ Open file in append mode.
If file does not exist, it creates a new file.
‘t’ This is the default mode. It opens in text mode.
‘b’ This opens in binary mode.
‘+’ This will open a file for reading and writing (updating)