Since the version of the main environment is 2.7, the information may be different after ver3.0. Please pardon.
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 "
.
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.
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.
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.
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.
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.
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.
There seems to be no big difference between 2.7 and 3.0.
https://tonari-it.com/python-os-walk/
Recommended Posts