1. Files
- Creating a file using open
import os
file_obj = open('data.txt', 'wt')
file_obj.close()
- 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
- 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
- Copying a file using copy()
import shutil
shutil.copy('source.txt', 'destination.txt')
shutil.move('old_name', 'new_name')
- Renaming a file using rename()
import os
os.rename('old_name.txt', 'new_name.txt')
- 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
- Modifying permissions using chmod()
import os
os.chmod('file.txt', 0o400)
import stat
os.chmod('file.txt', stat.S_IRUSR)
- Changing ownership using chown()
import os
uid = 5
gid = 22
os.chown('project', uid, gid)
- Getting the absolute path using abspath()
import os
# current working directory /home/user
os.path.abspath('file.txt') # /home/user/file.txt
- 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
- Deleting a file using remove()
import os
os.remove('file.txt')
2. Directories
- Creating a directory using mkdir()
import os
os.mkdir('new_folder')
- Removing a directory using rmdir()
import os
os.rmdir('folder_to_delete')
- 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']
- Changing the current directory using chdir()
import os
os.chdir('new_directory')
- 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
- 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
- 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()
- 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)
- Automatically closing a file using with
with open('output.txt', 'wt') as file:
file.write(content)
- Writing binary data using write()
byte_data = bytes(range(0, 256))
file = open('binary_file', 'wb')
file.write(byte_data)
file.close()
- Reading binary files using read()
file = open('binary_file', 'rb')
data = file.read()
file.close()