码迷,mamicode.com
首页 > 编程语言 > 详细

python文件,文件夹操作

时间:2019-11-04 13:19:20      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:misc   模块   导入   settings   lang   spec   asio   admin   ams   

首先,导入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

 

 

 

python文件,文件夹操作

标签:misc   模块   导入   settings   lang   spec   asio   admin   ams   

原文地址:https://www.cnblogs.com/cnapple/p/11791303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!