[Python beginner] What kind of files were there in this folder? When it becomes, search in one line.

Conclusion

Conclusion


os.listdir(path) 

Trigger

It all started when I wanted to list the documents in Downloads.

Details

Examine the path


#Method 1 option+command+C
#On Mac, you can get "absolute PATH" by pressing "option", "command", and "C" while selecting a file.
#Example:/Users/"User name"/Downloads/"File name"'

#Method 2
#Search for file names
#During study

Get files and folders with listdir



#This time, get the Downloads data
import os
path = '/Users/username/Downloads'
files = os.listdir(path)
for file in files:
    print(file)

Added: glob () is also useful

extension(.pdf)I want to check the file name by specifying


import glob
path = '/Users/username/Downloads'
print(glob.glob(path+'/*.pdf'))

If you want to search only now

I want to find out the path of the current file (absolute path)

Current directory


import os
print(os.getcwd())

For example, I'm writing python in spyder, so

/Users/username/.spyder-py3

Will be returned.

I want to check the current file by specifying the extension (.py) (file name)

Specify extension


import glob
glob.glob('*.py')

In the /Users/username/.spyder-py3 file

untitled0.py temp.py template.py history_internal.py history.py

Was returned when it was included.

Click here for convenient usage of glob How to use glob to recursively get a list of paths that satisfy the conditions in Python

Recommended Posts

[Python beginner] What kind of files were there in this folder? When it becomes, search in one line.
How to find out what kind of files are stored in S3 in Python
Decrypt one line of code in Python lambda, map, list
[Introduction to Udemy Python3 + Application] 32.1 When one line becomes long
Google search for the last line of the file in Python
Fizzbuzz in Python (in one line)
Get a list of files in a folder with python without a path
Make python segfault in one line
Handling of JSON files in Python
What kind of Kernel is this Kernel?
What kind of book is the best-selling "Python Crash Course" in the world?