Python File Operations with System Functions

1. Files

  1. Creating a file using open
import os
file_obj = open('data.txt', 'wt')
file_obj.close()
  1. Checking if a file or directory exists using exists()

Pass absolute or relative path. Returns True if exists, False otherwise.

import os
os.path.exists('config.txt')  # returns True
os.path.exists('..')   # True
  1. Checking if it is a file using isfile()
import os
os.path.isfile(name)  # checks if it is a file
os.path.isdir(name)   # checks if it is a directory
os.path.isabs(name)   # checks if it is an absolute path
  1. Copying a file using copy()
import shutil
shutil.copy('source.txt', 'destination.txt')
shutil.move('old_name', 'new_name')
  1. Renaming a file using rename()
import os
os.rename('old_name.txt', 'new_name.txt')
  1. Creating links using link() or symlink()

link() creates a hard link, symlink() creates a soft link.

import os
os.link('file1.txt', 'file2.txt')
os.path.islink('file2.txt') # False
os.symlink('file1.txt', 'file2.txt')
os.path.islink('file2.txt') # True
  1. Modifying permissions using chmod()
import os
os.chmod('file.txt', 0o400)
import stat
os.chmod('file.txt', stat.S_IRUSR)
  1. Changing ownership using chown()
import os
uid = 5
gid = 22
os.chown('project', uid, gid)
  1. Getting the absolute path using abspath()
import os
# current working directory /home/user
os.path.abspath('file.txt')  # /home/user/file.txt
  1. Getting the path of a symbolic link using realpath()
import os
# file.txt -> target.txt
os.path.realpath('file.txt') # returns the path of target.txt
  1. Deleting a file using remove()
import os
os.remove('file.txt')

2. Directories

  1. Creating a directory using mkdir()
import os
os.mkdir('new_folder')
  1. Removing a directory using rmdir()
import os
os.rmdir('folder_to_delete')
  1. Listing directory contents using listdir()
import os
os.listdir('folder')  # returns a list of files and subdirectories inside folder
folder
├── child_folder
│   └── file2.txt
└── file1.txt
import os
os.listdir('folder') # ['child_folder', 'file1.txt']
  1. Changing the current directory using chdir()
import os
os.chdir('new_directory')
  1. Listing matching files using glob()
  • matches any name ? matches one character [abc] matches a, b, or c [!abc] matches any character except a, b, or c
import glob
glob.glob('start*') # lists all files and directories starting with 'start'

3. File Input and Output

  1. Opening a file using open()
file = open(filename, mode)
# file is a file object
# filename is the file name
# mode: r (read), w (write, create if not exists), x (create if not exists), a (append if exists)
# t (text file), b (binary file)

file = open('data.txt', 'rb') # opens data.txt in binary read mode
  1. Writing to a text file using write()
content = 'Hello, world!'
file = open('output.txt', 'wt')
file.write(content)
file.close()

If the string is large, you can split it in to chunks and write incrementally:

content = '123456..................'
file = open('output.txt', 'wt')
offset = 0
chunk_size = 100
while offset < len(content):
    file.write(content[offset:offset+chunk_size])
    offset += chunk_size
file.close()
  1. Reading from a text file using read(), readline(), or readlines()

read() reads the entire file, readline() reads one line at a time, and readlines() reads all lines into a list.

file = open('input.txt', 'rt')
data = file.read()
file.close()
data = ''
file = open('input.txt', 'rt')
chunk_size = 100
while True:
    chunk = file.read(chunk_size)
    if not chunk:
        break
    data += chunk
file.close()

Using readline() to read line by line:

data = ''
file = open('input.txt', 'rt')
while True:
    line = file.readline()
    if not line:
        break
    data += line
file.close()

Using an iterator to read the file:

data = ''
file = open('input.txt', 'rt')
for line in file:
    data += line
file.close()

Using readlines() to get all lines as a list:

data = ''
file = open('input.txt', 'rt')
lines = file.readlines()
file.close()
for line in lines:
    print(line)
  1. Automatically closing a file using with
with open('output.txt', 'wt') as file:
    file.write(content)
  1. Writing binary data using write()
byte_data = bytes(range(0, 256))
file = open('binary_file', 'wb')
file.write(byte_data)
file.close()
  1. Reading binary files using read()
file = open('binary_file', 'rb')
data = file.read()
file.close()

Tags: python file operations System Functions

Posted on Sat, 06 Jun 2026 17:21:37 +0000 by hostcord