文件和文件夹的操作

1,基本操作

# hanbb
# come on!!!
import os

# 文件名称
path = os.path.join('usr','bin','spam')                        # 通过函数来设置文件夹
print(path)
myfiles = ['accounts.txt','details.doc','invite.docx']         # 文件列表
for file in myfiles:
    print(os.path.join('C:','users','asweight',"{}").format(file))
# 当前目录
print(os.getcwd())    # 获得当前工作目录
# os.chdir(path=)     # 更改当前工作目录

# 绝对路径和相对路径
'''
绝对路径:总是从根目录开始
相对路径,相对于程序的当前工作目录
 . 表示这个目录 ..表示父文件夹
'''
# 检测是否存在,若不存在则创建

# 先定义一个带路径的文件
path = 'E:\python\file'
# 判断文件路径是否存在
if os.path.exists(path):
    print('文件已存在')
# 如果不存在,则创建
else:
    os.makedirs(path)

path2 = os.path.join('C:','file','lianxin')
if os.path.exists(path2):
    print("文件已经存在")
else:
    os.makedirs(path2)
    print('文件创建完成')

# 创建新文件夹
'''
path2 = os.path.join('C:','file','lianxin') # 文件路径设置 通过函数写入
os.makedirs(path2)                          # 创建
path3 = 'C:\file\lianxi2'                 # 直接输入,记得是两个斜杠
os.makedirs(path3)
'''

# 路径返回 分解
path4 = 'C:\users\asweight\invite.docx'
print(os.path.dirname(path4))    # 文件夹 (不包括文件名)
print(os.path.basename(path4))   # 文件名  (没有文件夹信息)
print(os.path.split(path4))      # 将文件夹和文件名分解开,并保存到一个元组里面

# 查看文件大小和文件夹内容
path5 = "E:\solvent effect"
print(os.path.getsize(path5))       # 文件的大小
print(os.listdir(path5))            # 文件夹下面的东西

totalsize = 0                       # 综合利用
for file in os.listdir('E:\solvent effect'):
    totalsize = totalsize + os.path.getsize(os.path.join('E:\solvent effect',file))
print(totalsize)

#

2,小工具和文件的读取,写入

# hanbb
# come on!!!

import os
# 检测存在
path = 'C:\Users\HBB\Desktop\hello.txt'
# 判断文件路径是否存在
if os.path.exists(path):
    print('文件存在')
# 如果不存在,则创建
else:
    os.makedirs(path)

# 文件打开
hellofile = open("C:\Users\HBB\Desktop\hello.txt") # 默认只读模式 open("C:\Users\HBB\Desktop\hello.txt,‘r")

# 文件读取
hellocontent = hellofile.read()            # 读取全部内容
print(hellocontent)
# hellocontent = hellofile.readlines()     # 按行读取
# hellocontent = hellofile.readline(5)     # 可以限制读取行的范围

# 文件写入
writefile = open(path,'w')                 # 写入已有文件

writefile =open('hellowrite.txt',"w")      # 写入文件,注意对于文件已经有的东西会全部覆盖掉
writefile.write("hello,world!
")
writefile.close()

writefile = open('hellowrite.txt',"a")     # 新写入的添加到后面
writefile.write('我是新添加的,append')
writefile.close()

writefile = open('hellowrite.txt')
print(writefile.readlines())
writefile.close()
原文地址:https://www.cnblogs.com/hanbb/p/7891847.html