Examples for Opening Files



In [ ]:
#This is how you import libraries
import os
import csv
import sys

In [ ]:
#This is how you check your version of Python
sys.version

In [ ]:
#This command shows the current working directory (what open uses for for relative paths).
os.getcwd()

In [ ]:
#This is how you change the current working directory (what open uses for for relative paths).
os.chdir('C:\\')
os.getcwd()

In [ ]:
#This is how you revert the current working directory (what open uses for for relative paths).
os.chdir(os.path.expanduser('~'))
os.getcwd()

In [ ]:
#this is how to open a CSV file in Python 3

userhome = os.path.expanduser('~')
csvfile = userhome + '\\Desktop\\test.csv'
with open(csvfile, "r") as f:
    csvReader = csv.reader(f)  #csv.reader is a built-in Python function
    print(next(csvReader))
    print("This is a comment to separate commands")
    print(next(csvReader))

In [ ]:
#this is how to open a txt file in Python 3

userhome = os.path.expanduser('~')
txtfile = userhome + '\\Desktop\\test.txt'
with open(txtfile, "r") as f:
    wordsFile = f.read().splitlines()
len(wordsFile)