python編程,python類的應用_python中文件類的應用

 2023-10-13 阅读 30 评论 0

摘要:python中對文件、文件夾的操作需要涉及到os模塊和shutil模塊。創建文件:1) os.mknod("test.txt") 創建空文件2) open("test.txt",w) 直接打開一個文件,如果文件不存在則創建文件創建目錄:python編程。os.mkdir("file") 創建目錄

python中對文件、文件夾的操作需要涉及到os模塊和shutil模塊。

創建文件:

1) os.mknod("test.txt") 創建空文件

2) open("test.txt",w) 直接打開一個文件,如果文件不存在則創建文件

創建目錄:

python編程。os.mkdir("file") 創建目錄

os.makedirs('file') 創建多級目錄

復制文件:

shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件

shutil.copy("oldfile","newfile") oldfile只能是文件夾,newfile可以是文件,也可以是目標目錄

復制文件夾:

python讀取csv文件、shutil.copytree("olddir","newdir") olddir和newdir都只能是目錄,且newdir必須不存在

重命名文件(目錄)

os.rename("oldname","newname") 文件或目錄都是使用這條命令

移動文件(目錄)

shutil.move("oldpos","newpos")

刪除文件

python web。os.remove("file")

刪除目錄

os.rmdir("dir") 只能刪除空目錄

shutil.rmtree("dir") 空目錄、有內容的目錄都可以刪

轉換目錄

os.chdir("path") 換路徑

python和java、判斷目標

os.path.exists("goal") 判斷目標是否存在

os.path.isdir("goal") 判斷目標是否目錄

os.path.isfile("goal") 判斷目標是否文件

os.walk遍歷rootdir的根目錄,返回父目錄名字,文件夾名字列表,文件名字列表

#for parent,dirnames,filenames in os.walk(rootdir):

python3。#????????for dirname in dirnames:

#????????????????print "parent is :"+parent

#????????????????print "dirname is :"+dirname

#????????????????if dirname.startswith('Day'+)

#

#????????for filename in filenames:

Python的類、#????????????????print "parent is:"+parent

#????????????????print "filename is :"+filename

#????????????????print "the full name of the file is:"+os.path.join(parent,filename)#組合在一起

批量從某個目錄下復制東西到新的目錄:

#coding=UTF-8

import os

python怎么運行py文件,import os.path

import shutil

oldrootdir=r'F:\安卓學習\Android'

newrootdir=r'F:\安卓學習\打包代碼-送人'

i=10

for olddirname in os.listdir(oldrootdir):

python應用領域、if olddirname.startswith('Day'+str(i)):

print olddirname

i+=1

for olddestname in os.listdir(oldrootdir+'\\'+olddirname):

baseoldname=oldrootdir+'\\'+olddirname

if olddestname.startswith("PPT"):

python 讀文件、shutil.copytree(baseoldname+'\\'+olddestname,newrootdir+'\\'+olddirname+'\\'+olddestname)

if olddestname.startswith("作業"):

shutil.copytree(baseoldname+'\\'+olddestname,newrootdir+'\\'+olddirname+'\\'+olddestname)

批量刪除目錄:

#coding=UTF-8

import os

Python中的類,name=r'F:\安卓學習\打包代碼-送人'

i=1

for dirname in os.listdir(name):

if dirname.__eq__('DAY0'+str(i)):

os.rmdir(name+'\\'+dirname)

i+=1

python怎么打開文件、判斷大小篩選:

#coding=UTF-8

import os

name=r'F:\代碼Demo習題集\python\python代碼\爬蟲'

for jpgname in os.listdir(name):

if jpgname.endswith('.jpg'):

python中的類和對象。size=os.path.getsize(jpgname)

if size<200000:

os.remove(jpgname)

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/135898.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息