HomeToolsAbout

Files and Directories

os

os module provides functions to interact with the operating system

import os

Directory Operations

# Current Directory current_dir = os.getcwd() # List all files and directories in cwd files = os.listdir(current_dir)

File Operations

open Built-in Function

Open file and return a corresponding file object

  • If the file cannot be opened, an OSError is raised
some_file = open(file_location, "r")

readlines()

Return all lines in the file, as a list where each line is an item in the list object

# "r" is to hard-define operation as read f = open("demofile.txt", "r") print(f.readlines()) # ['Hello! Welcome to demofile.txt\n', 'This file is for testing purposes.\n', 'Good Luck!']
AboutContact