python文件操作脚本

1、使用opencv批量压缩图片

import cv2
import os
import time
#需要压缩的图片路径
path='test'  
#压缩后图片存放路径
result='test_result'
#dir为列表,包含path下所有的图片名
dir = os.listdir(path)
print('需要压缩的图片数为:'+str(len(dir)))
count = 1
for i in dir:
    print('正在压缩第{}张图片'.format(count),end = ',')
    start=time.time()
    img=cv2.imread(path+'/{}'.format(i))
    #用0-100的整数表示,数值越大质量越高,默认为95。 注意,cv2.IMWRITE_JPEG_QUALITY类型为Long,必须转换成int;
    #对于PNG,第三个参数表示的是压缩级别。cv2.IMWRITE_PNG_COMPRESSION,从0到9,压缩级别越高,图像尺寸越小。
    cv2.imwrite(result+'/{}'.format(i),img,[int(cv2.IMWRITE_JPEG_QUALITY), 10])
    end=time.time()
    print('压缩第{}张图片耗时{}'.format(count,end-start))
    count+=1

2、批量修改图片像素

import os
from PIL import Image
import glob

def convertjpg(jpgfile,outdir,width=300,height=225):  #300-255位修改后的图片大小
    img=Image.open(jpgfile)   
    new_img=img.resize((width,height),Image.BILINEAR)   
    new_img.save(os.path.join(outdir,os.path.basename(jpgfile)))
    
for jpgfile in glob.glob("test/*.jpg"):   #test为需要修改图片的目录
    convertjpg(jpgfile,"test_result")	#test_result为修改后图片的保存目录

3、批量修改指定目录下文件的名字

方法一:修改为类似cup1.jpg...的格式

import os

path = 'test'  #要修改的图片目录
count = 1

for i in os.listdir(ipath):
    #print(i)
    old_name = os.path.join(path, i)
    new_name = os.path.join(path, 'cup{}.jpg'.format(count))    #修改后的新名字
    count += 1
    if count >100: break
    os.rename(old_name,new_name)
    

方法2:修改为类似name_0001.jpg...的格式

import os

def formatting(count):
    strcount=str(count)
    if len(strcount)==1:
        #print('000'+strcount)
        return '000'+strcount
    elif len(strcount)==2:
       # print('00' + strcount)
        return '00'+strcount
    elif len(strcount)==3:
       # print('0' + strcount)
        return '0'+strcount
    elif len(strcount)==4:
       # print(strcount)
        return strcount

def rename():
    count=0
    path='test'

    filelist=os.listdir(path)
    for files in filelist:
        Olddir=os.path.join(path,files)#原路径
        filename=os.path.splitext(files)[0]#文件名
        filetype=os.path.splitext(files)[1]#文件扩展名
        Newdir=os.path.join(path,'name_'+formatting(count)+filetype)#新的文件路径
        os.rename(Olddir,Newdir)
        count+=1
    print('success')

rename()

4、删除指定目录下所有文件

import os

def del_file(path):
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_file(c_path)
        else:
            os.remove(c_path)
            
            
path = 'test'  #删除test目录下所有图片
del_file(path)

5、删除指定目录下指定后缀的文件

import os
import glob

path ='test/*.jpg'  #要删除的指定目录
for infile in glob.glob(path):
     os.remove(infile)

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Python 中读写文件非常简单。 读取文件: ```python # 打开文件 f = open("example.txt", "r") # 读取文件内容 content = f.read() # 关闭文件 f.close() # 输出文件内容 print(content) ``` 写入文件: ```python # 打开文件 f = open("example.txt", "w") # 写入文件内容 f.write("Hello, world!") # 关闭文件 f.close() ``` 另外, 也可以使用 'with' 语句来简化文件读写过程,避免忘记关闭文件导致资源泄漏 读取文件: ```python with open("example.txt", "r") as f: content = f.read() print(content) ``` 写入文件: ```python with open("example.txt", "w") as f: f.write("Hello, world!") ``` ### 回答2: Python操作读写文件脚本非常简单,可以用一些内置函数和方法来实现。 首先,要读取文件内容,可以使用`open`函数打开文件,该函数接收文件路径和打开模式作为参数。例如,要读取名为`myfile.txt`的文件,可以使用以下代码: ``` file = open("myfile.txt", "r") content = file.read() file.close() ``` 上述代码使用了`open`函数来打开文件,通过设置模式为"r"来指定只读模式。然后,可以使用`read`方法来读取文件内容,并将其存储在`content`变量中。最后,使用`close`方法关闭文件。 接下来,如果要写入文件内容,可以使用`open`函数打开文件,并指定打开模式为写入模式"w"。例如,要将文本写入名为`myfile.txt`的文件,可以使用以下代码: ```python file = open("myfile.txt", "w") file.write("Hello, World!") file.close() ``` 上述代码使用了`open`函数来打开文件,然后使用模式"w"来指定写入模式。接着,使用`write`方法将文本写入文件。最后,使用`close`方法关闭文件。 值得注意的是,使用`write`方法写入文件时,如果文件已经存在,会将原有内容清空并覆盖。如果想要在文件末尾添加内容而不是覆盖原有内容,可以使用追加模式"a"来打开文件。 以上就是使用Python操作读写文件的基本脚本。当然,还有其他更复杂的读写文件的方法,包括逐行读取、指定编码等,但这些基本操作足以满足大多数需求。 ### 回答3: Python提供了丰富的方法来操作读写文件。首先需要用open()函数来打开文件,可以指定文件名和打开方式(只读、写入、追加、二进制读写等)。比如,我们可以用以下代码来打开一个文件并读取内容: ```python with open("example.txt", "r") as file: content = file.read() ``` 这段代码会打开名为example.txt的文件并将其内容读取到变量content中。读取文件时,常用的方法有read()、readline()和readlines()。其中,read()会读取整个文件内容,readline()会逐行读取文件内容,而readlines()则会将文件内容读取为一个列表。 如果要写入文件,可以使用open()函数的"w"或"a"参数来指定写入方式。其中,"w"表示写入模式,会覆盖原有文件内容,而"a"表示追加模式,会在原有文件内容的末尾添加新内容。例如: ```python with open("example.txt", "a") as file: file.write("Hello, World!") ``` 这段代码会在名为example.txt的文件末尾添加一行内容"Hello, World!"。除了write()方法,还可以使用writelines()方法来写入多行内容。 另外,可以使用os模块来操作文件相关的功能,比如重命名文件、删除文件等。例如,使用os.rename()函数来重命名文件: ```python import os os.rename("old.txt", "new.txt") ``` 这段代码会将名为old.txt的文件重命名为new.txt。 总之,Python提供了简单且灵活的方法来操作读写文件,通过open()函数和相关方法,可以轻松实现对文件的读取和写入操作
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值