current position：Home>Common OS operations for Python
Common OS operations for Python
2022-01-30 03:42:33 【Clever crane】
Little knowledge , Great challenge ！ This article is participating in “ A programmer must have a little knowledge ” Creative activities .
1. Get all files in the current directory
have access to
os.listdir(path) function , It can return to
path The specified folder contains
Folder A list of names .
How to use it is as follows ：
import os # Open file path = "D://data/" dirs = os.listdir( path ) # Output all files and folders for file in dirs: print (file) Copy code
2. Traverse folders, including subfolders
have access to
os.walk(path) function , It can traverse all the files in the directory by swimming through the directory tree .
It returns a triple
(root, dirs, files) The generator ,
rootIt refers to the address of the folder being traversed
list, The contents are the names of all the directories in the folder （ Exclude subdirectories ）
list, The content is all the files in the folder （ Exclude subdirectories ）
How to use it is as follows ：
import os path = "D://data/" for root, dirs, files in os.walk(path): for name in files: print(os.path.join(root, name)) for name in dirs: print(os.path.join(root, name)) Copy code
3. Other commonly used OS operation
In addition, there are some commonly used
os operation , Such as
os.path.exists(path)Used to determine
pathDoes the path exist , return
os.makedirs(path)Used to create
For example, when downloading files , Hope you can
Breakpoint continuation , That is, when downloading a file , First judge whether the file exists in the local path .
if not os.path.exists(path): #todo: download file downloadFile(path) else: pass Copy code
Sometimes when saving files , If the path does not exist, it may fail to save and report an error , So you can first judge whether the path exists , If it does not exist , First create .
if not os.path.exists(path): # create path os.makedirs(path) # todo: save file saveFiles() Copy code
author[Clever crane],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Getting started with Python - object oriented - special methods
- Using linear systems in python with scipy.linalg
- Fast power modulus Python implementation of large numbers
- Python architects recommend the book "Python programmer's Guide" which must be read by self-study Python architects. You are welcome to take it away
- Decoding the verification code of Taobao slider with Python + selenium, the road of information security
- Python game development, pyGame module, python implementation of skiing games
- Python collects and monitors system data -- psutil
- Python + selenium automated test: page object mode
- You can easily get started with Excel. Python data analysis package pandas (IV): any grouping score bar
- Python ThreadPoolExecutor restrictions_ work_ Queue size
guess what you like
Python generates and deploys verification codes with one click (Django)
[Python kaggle] pandas basic exercises in machine learning series (6)
Using linear systems in python with scipy.linalg
Using Python to realize national second-hand housing data capture + map display
How to make Python run faster? Six tips!
Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
This pandas exercise must be successfully won
[algorithm learning] sword finger offer 64 Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
Understand Python's built-in function and add a print function yourself
Python implements JS encryption algorithm in thousands of music websites
- leetcode 35. Search Insert Position（python）
- [introduction to Python visualization]: 12 small examples of complete data visualization, taking you to play with visualization ~
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary（python）
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)（python）
- Teach you to read the source code of Cpython (I)
- Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
- leetcode 88. Merge Sorted Array（python）
- Don't you know more about a python library before the end of 2021?
- Python crawler web page parsing artifact XPath quick start teaching!!!
- Use Python and OpenCV to watermark the image
- String and related methods of Python data type introduction
- Heapq module of Python module
- Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
- Event loop of Python collaboration series
- Django docking pin login system
- [recalling the 1970s] using Python to repair the wonderful memories of parents' generation, black-and-white photos become color photos
- You used to know Python advanced
- Pyinstaller package Python project
- 2021 IEEE programming language rankings: Python tops the list!
- Implementation of Python automatic test control
- Python advanced: [Baidu translation reverse] graphic and video teaching!!!
- Do you know the fuzzy semantics in Python syntax?
- [Python from introduction to mastery] (XXVII) learn more about pilot!
- Playing excel office automation with Python
- Some applications of heapq module of Python module
- Python and go languages are so popular, which is more suitable for you?
- Python practical skills task segmentation
- Python simulated Login, numpy module, python simulated epidemic spread
- Python opencv contour discovery function based on image edge extraction
- Application of Hoff circle detection in Python opencv
- Python reptile test ox knife (I)
- Day 1: learn the Django framework of Python development
- django -- minio_ S3 file storage service
- [algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
- Learning in Python + opencv -- extracting corners