File / folder path manipulation in Python

File / folder path manipulation in Python

Since the version of the main environment is 2.7, the information may be different after ver3.0. Please pardon.

<Os.path.exists> Check the existence of folders and files

Whether the folder exists

import os
folderpath = ("C:\\test_folder\\test1")
print(os.path.exists(folderpath))
# True

You can check if the specified folder exists by using os.path.exists. The result is returned as bool.

** Be careful of the escape sequence \ when specifying the folder path. ** ** Add r and write r" C: \ Users \ xxx \ desktop \ xxx " or Alternatively, you can use \\ to recognize \ as a character string and write " C: \\ Users \\ xxx \\ desktop \\ xxx ".

Whether the file exists

import os
filepath = ("C:\\test_folder\\test1\\sample.txt") 
print(os.path.exists(filepath))
# True

If you specify the file name directly, you can check the existence of the file.

<Os.path.isfile> Judge that the file exists

import os
filepath = ("C:\\test_folder\\test1\\sample") 
print(os.path.isfile(filepath))

# True

True is returned if the specified file exists. If it is a folder or the file does not exist, False is returned.

Judge that the <os.path.isdir> folder exists

import os
filepath = ("C:\\test_folder\\test1") 
print(os.path.isdir(filepath))

# True

True is returned if the specified folder exists. If it is a file, or if it does not exist, False is returned.

Examine the details of the files in the <os.listdir> folder

import os
folderpath = ("C:\\test_folder\\test1")
print(os.listdir(folderpath))

#['test2''test1.bmp','test1.txt']

The files and folders that exist in the specified folder are stored in the list. The data in the subfolders will not be displayed.

<Os.walk> Check the contents of the subfolder

import os

filepath = ("C:\\test_folder\\test1")  
for i in os.walk(filepath):
    print(i)

#('C:\\test_folder\\test1', ['test2'], ['test1-A.txt', 'test1-B.txt'])
#('C:\\test_folder\\test1\\test2', [], ['test2-A.txt', 'test2-B.txt'])

A tuple is created. It consists of three elements (folder path, subfolder name, file name). The output information is appropriate.

Example) Extract only the file name

import os

filepath = ("C:\\test_folder")  
for folder,subfolder,filename in os.walk(filepath):
    print(filename)

#['test1-A.txt', 'test1-B.txt']
#['test2-A.txt', 'test2-B.txt']

The for statement is turned with the three elements of folder, subfolder, and filename, and only the filename is printed. It is necessary to process the data when actually using it.

Summary

There seems to be no big difference between 2.7 and 3.0.

Referenced page

https://tonari-it.com/python-os-walk/

Recommended Posts

File / folder path manipulation in Python
File operations in Python
File processing in Python
String manipulation in python
Date manipulation in Python
File operations in Python
Download the file in Python
Naturally sort Path in Python
String date manipulation in Python
Pixel manipulation of images in Python
[Python] Open the csv file in the folder specified by pandas
[Python] Create a file & folder path specification screen with tkinter
Save the binary file in Python
Linebot creation & file sharing in Python
Get the desktop path in Python
Calculate free-space path loss in Python
Get the script path in Python
Create a binary file in Python
Python memo ① Folder and file operations
Get the desktop path in Python
ORC, Parquet file operations in Python
Project Euler # 15 "Lattice Path" in Python
Read a file in Python with a relative path from the program
Get a list of files in a folder with python without a path
Exclusive control with lock file in Python
Convert psd file to png in Python
Write O_SYNC file in C and Python
Read the file line by line in Python
Read the file line by line in Python
Exclusive file access between processes in Python
See file and folder information on python
[GPS] Create a kml file in Python
[Python] Read the specified line in the file
Python in optimization
CURL in python
Script python file
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Python Grammar-String Manipulation
Meta-analysis in Python
A memo organized by renaming the file names in the folder with python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
Python file processing
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python