Python 技术点

1、文件操作

1-1 遍历文件夹和文件


import os
rootDir = "/path/to/root"

for parent, dirnames, filenames in os.walk(rootDir):
    for dirname in dirnames:
        print("parent is:" + parent)
        print("dirname is:" + dirname)
    
    for filename in filenames:
        print("parent is:" + parent)
        print("filename is:" + filename)
        print("the full name of the file is:" + os.path.join(parent, filename))

1-2 获取文件名和扩展名


import os
path = "/root/to/filename.txt"

name, ext = os.path.splitext(path)
print(name, ext)
print(os.path.dirname(path))
print(os.path.basename(path))

1-3 逐行读取文本文件内容


f = open("/path/to/file.txt")

# The first method
line = f.readline()
while line:
    print(line)
    line = f.readline()
f.close()

# The second method
for line in open("/path/to/file.txt"):
    print(line)

# The third method
lines = f.readlines()
for line in lines:
    print(line)

1-4 写文件


output = open("/path/to/file", "w")
# output = open("/path/to/file", "w+")

output.write(all_the_text)
# output.writelines(list_of_text_strings)

1-5 判断文件是否存在


import os

os.path.exists("/path/to/file")
os.path.exists("/path/to/dir")

# Only check file
os.path.isfile("/path/to/file")

1-6 创建文件夹


import os

# Make multilayer directorys
os.makedirs("/path/to/dir")

# Make single directory
os.makedir("/path/to/dir")

(未完待续)

来源:https://segmentfault.com/a/1190000018225184

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值