Python的简单文件操作

import os #导入os模块
nowPath=os.getcwd() #获取当前文件的工作路径
print(nowPath)

changePath=os.chdir(‘C:\Users\user\Desktop’) #改变当前工作路径
print(os.getcwd())

#makeDir=os.makedirs(‘C:\Users\user\Desktop\AAA\BBB’) #创建文件夹

absolutePath=os.path.abspath(’.\Desktop\AAA\BBB’) #将相对路径转换为绝对路径
print(absolutePath)
isAbsolutePath=os.path.isabs(‘C:\Users\user\Desktop\AAA\BBB’) #判断该路径是否为绝对路径
print(isAbsolutePath)

fileLen=os.path.getsize(‘C:\Users\user\Desktop\AAA\BBB\1.txt’) #获取文件的字节数
print(fileLen)
fileList=os.listdir(‘C:\Users\user\Desktop\AAA\BBB’) #以列表的形式返回该目录下文件名称
print(fileList)

isDirOrFile=os.path.exists(‘C:\Users\user\Desktop\AAA\BBB’) #判断路径所指是否为文件或文件夹(返回True或False)
print(isDirOrFile)
isDir=os.path.isdir(‘C:\Users\user\Desktop\AAA\BBB’) #判断路径所指是否为文件夹
print(isDir)
isFile=os.path.isfile(‘C:\Users\user\Desktop\AAA\BBB\1.txt’) #判断路径所指是否为文件
print(isFile)

helloFile1=open(‘C:\Users\user\Desktop\AAA\BBB\1.txt’) #返回一个文件对象
#readFile=helloFile1.read() #读取文件,read(n),n表示要读取的从头开始的字节数
#print(readFile)
readFileLine=helloFile1.readlines() #读取文件的内容,并以列表的形式返回每行的内容
print(readFileLine)

helloFile2=open(‘C:\Users\user\Desktop\AAA\BBB\2.txt’,‘w’) #以写入纯文本模式返回一个对象
writeFile=helloFile2.write(‘123\nqwer’) #写入内容(以写入模式添加会覆盖原有文件的内容)
helloFile2.close()

helloFile3=open(‘C:\Users\user\Desktop\AAA\BBB\2.txt’,‘a’) #以添加纯文本模式返回一个对象
addFile=helloFile3.write(’\nasdffa2233’) #写入内容(以添加模式添加不会覆盖原有文件的内容,在末尾继续添加)
helloFile3.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值