Skip to content

Files in Python3

Check if file, directory, or both exists

import os
raw_path  = "/etc"
file_path = "/etc/crontab"
something_exists = os.path.exists(path_to_file)
path_exists = os.path.isdir()
file_exists = os.path.isfile()
dir_list    = os.listdir(path)

Create a directory

List files in directory

glob

Read first n lines in python

Read file without new line character

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')

Write list to text file

MyList = ["New York", "London", "Paris", "New Delhi"]

MyFile=open('output.txt','w')
MyFile.writelines(MyList)
MyFile.close()

Write file

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()