Popular File related problems and solutions using Python
Tags: python, python file process, python tutorialWe share clean solutions for some of the most popular questions you may encounter when you process files or directories using Python.
-
How to check whether a file exists using Python?
12import os.pathos.path.exists(file_path) -
How to check whether a path is a file?
You can use the os.path.isfile function:
It returns True if path is an existing regular file. This follows symbolic links, so both islink() andisfile() can be true for the same path.12import os.pathos.path.isfile(fname) -
How to make sure an directory exist?
12345678910import osimport errnodef ensure_dir_exist(path):try:if not os.path.exists(path):os.makedirs(path)except OSError as exception:if exception.errno != errno.EEXIST:raise -
How to list all files of a directory in Python
1234from os import listdirfrom os.path import isfile, joinpath ="/"onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]or
1234567from os import walkf = []for (dir_path, dir_names, file_names) in walk(path):f.extend(file_names)break -
How to read a file line by line into a list with Python
12345lines = []with open("file.txt", "r") as f:for line in f:line = line.strip() # process your line herelines.append(line) -
How to append a line to file in Python?
12with open("test.txt", "a") as f:f.write("new line") -
How to remove a file in Python?
os.remove()
will remove a file.os.rmdir()
will remove an empty directory.shutil.rmtree()
will delete a directory and all its contents.os.remove('test.txt')
will remove file test.txt from the current working directory.os.remove('/home/user/test.txt')
will remove/home/user/test.txt
Please leave a comment if you want to add more problems and solutions.