学习-Python文件之目录访问

第1关 学习-Python文件之目录访问

1
2
3
4
5
6
7
8
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
########## Begin ##########
# 第一步:打印当前的工作路径
import os
os.getcwd()
# 第二步:打印当前目录下的所有文件以及文件夹的列表
print(os.listdir())
########## End ##########

基于Python语言的文件与文件夹管理

第1关 创建子文件夹

1
2
3
4
5
6
import os
def mkDir():
    # ÇëÔÚÕâÀï²¹³ä´úÂ룬Íê³É±¾¹ØÈÎÎñ
    #-----------Begin----------
    os.mkdir("dst")
    #------------End-----------

第2关 删除带有只读属性的文件

1
2
3
4
5
6
7
8
import os, sys
import os.path
def removeFile():
    #-----------Begin----------
    fn = os.path.join(sys.path[0],r'src/removeme.txt')
    os.chmod(fn, 0o444)
    os.remove(fn)
    #------------End-----------

第3关 批量复制文件夹中的所有文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
import os.path
import shutil
def copyTree(src, dst):
    #-----------Begin----------
    total=0
    def copy(src,dst):
        nonlocal total
        for item in os.listdir(src):
            srcPath=os.path.join(src,item)
            dstPath=os.path.join(dst,item)
            if os.path.isdir(srcPath):
                os.makedirs(dstPath)
                total += 1
                copy(srcPath,dstPath)
            elif os.path.isfile(srcPath):
                shutil.copyfile(srcPath,dstPath)
                total += 1
    copy(src,dst)
    return total
    #------------End-----------

学习-Python文件之二进制文件的读写

第1关 学习-Python文件之二进制文件的读写

1
2
3
4
5
6
7
8
# 请在下面的 Begin-End 之间按照注释中给出的提示编写正确的代码
########## Begin ##########
# 使用 input 函数获取读取的字节数并打印读取的二进制文件的内容
with open('src/step1/test.png', 'rb') as f:
    num = int(input())
    content = f.read(num)
    print(content)
########## End ##########

学习-Python文件之文本文件的读取

第1关 学习-Python文件之文本文件的读取

1
2
3
4
5
6
# 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
########## Begin ##########
# 使用 open 函数打开文件,打印文件的打开方式
f=open("src/step1/data.txt","w",encoding="utf8")
print(f"文件打开方式为:{f.mode}")
########## End ##########