python文件,文件夹操作

首先,导入os模块

1 import os

获取当前文件所在文件夹的路径,getcwd()

更改当前目录:chdir()

创建文件夹,mkdir()

获取文件夹下所有子文件夹及文件,listdir()

判断是否是文件夹os.path.isdir()

更改文件名称,rename(old_name, new_name)

删除文件夹,rmdir()

import os

path = os.getcwd()
print(path)
# os.chdir('c:\\')
#
# path = os.getcwd()
# print(path)
contents = os.listdir()
for content in contents:
    if os.path.isfile(content):
        print(content)
        # print("-----------------")
    elif os.path.isdir(content):
        print(content)
        print('----------------')
        contents_sub = os.listdir(content)
        for content_sub in contents_sub:
            print(content_sub)

运行结果:

 1 C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe C:/Users/Administrator/PycharmProjects/oo_test/file_folder_test01.py
 2 C:\Users\Administrator\PycharmProjects\oo_test
 3 .idea
 4 ----------------
 5 encodings.xml
 6 inspectionProfiles
 7 misc.xml
 8 modules.xml
 9 oo_test.iml
10 workspace.xml
11 00_test.py
12 abnormity
13 ----------------
14 add_test.py
15 alice.txt
16 f_not_found_test.py
17 zerodivisionerror_test.py
18 alien
19 ----------------
20 alien_invasion.py
21 bullet.py
22 game_functions.py
23 images
24 settings.py
25 ship.py
26 __pycache__
27 car_test
28 ----------------
29 car.py
30 my_car.py
31 __pycache__
32 chapter10
33 ----------------
34 copy_test.py
35 file_fold_twst
36 file_management.py
37 file_read.py
38 file_write.py
39 greet_user.py
40 json_name.json
41 json_test.py
42 json_test1.py
43 json_text-副本..txt
44 json_text.json
45 json_text.txt
46 pi_digits.txt
47 pi_million_digits.txt
48 programming-副本..txt
49 programming.txt
50 programming1.txt
51 seek.py
52 seek_test.txt
53 username.json
54 favorite_languages.py
55 fenxing_tree
56 ----------------
57 fenxing_test.py
58 fenxing_tree_02.py
59 fenxing_tree_test.py
60 file_folder_test01.py
61 get_evet_test.py
62 money_challenge
63 ----------------
64 money_saving_01.py
65 money_saving_02.py
66 money_saving_03.py
67 money_saving_04.py
68 oo-1
69 ----------------
70 object_test.py
71 prime_number.py
72 recursion_test.py
73 title_test.txt
74 yuiop.py

 

 

 

posted @ 2019-11-04 11:49  不帅用砖拍  阅读(457)  评论(0编辑  收藏  举报