一些Linux文件操作和Python操作集合

1.将一个文件夹下的某种文件(如jpg)移动到一个新的文件夹

import os
import shutil
import tqdm

old_path = '/root/xinyuan/datasets'
new_path = '/root/xinyuan/resiscpng/'
       
for root, dirs, files in os.walk(old_path, topdown=True):
    for file in files:
        if file.endswith(".jpg") : 
            shutil.move(os.path.join(root, file), os.path.join(new_path, file))

2.将一个大文件夹(包含子文件夹)的tiff文件转为png文件后输出到一个新文件夹

#将一个大文件夹(包含子文件夹)下的tiff文件转为png文件后输出到一个文件夹

import os
import cv2

# TIF_img_dir为输入TIF文件夹
# PNG_img_dir为输出PNG文件夹
def Tif_To_Png(TIF_img_dir, PNG_img_dir):
    # 创建输出目录
    if os.path.exists(PNG_img_dir):
        pass
    else:
        os.mkdir(PNG_img_dir)
    TIF_names = os.listdir(TIF_img_dir)
    for name in TIF_names:
        absolute_path = TIF_img_dir + '/' + name
        TIF_image = cv2.imread(absolute_path)
        # print(PNG_img_dir + '/' + name[:-3] + 'png')
        # print(TIF_image)
        cv2.imwrite(PNG_img_dir + '/' + name[:-3] + 'png', TIF_image)
        
def get_dirlist():
    Filedirs = [] 
    for home, dirs, files in os.walk(TIF_path):
        for dirname in dirs:
            # 文件夹列表,包含完整路径
            Filedirs.append(os.path.join(home, dirname))
    return Filedirs
        
if __name__ == '__main__':
    #原来的大文件夹路径
    TIF_path = '/root/xinyuan/datasets/UCMerced_LandUse/Images'
    #新文件夹路径
    PNG_dir = '/root/xinyuan/datasets/UCMLandPng'
    Filedirs = get_dirlist()
    #子文件夹个数
    print(len(Filedirs))
    for filedir in Filedirs:
        Tif_To_Png(filedir,PNG_dir)

3.将一个大文件夹下的所有分文件夹下的文件复制到一个新文件夹

import os
import shutil

def CreateDir(path):
    isExists=os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        os.makedirs(path) 
        print(path+' 目录创建成功')
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(path+' 目录已存在')

def CopyFile(filepath, newPath):
    # 获取当前路径下的文件名,返回List
    fileNames = os.listdir(filepath) 
    for file in fileNames:
        # 将文件命加入到当前文件路径后面
        newDir = filepath + '/' + file 
        # 如果是文件
        if os.path.isfile(newDir):  
            print(newDir)
            newFile = newPath + file
            shutil.copyfile(newDir, newFile)
        #如果不是文件,递归这个文件夹的路径            
        else:
            CopyFile(newDir,newPath)                

if __name__ == "__main__":
    path = '/root/xinyuan/datasets/NWPU-RESISC45'
    # 创建目标文件夹
    mkPath = '/root/xinyuan/datasets/respng/'
    CreateDir(mkPath)
    CopyFile(path,mkPath)

4.利用opencv 批量将jpg格式图像转png图像(文件大小会变大[约扩大8倍左右],因为是非直接改后缀名)

import os
import cv2

def transform(input_path, output_path):
    for root, dirs, files in os.walk(input_path):
        for name in files:
            file = os.path.join(root, name)
            print('transform   ' + name  + " to  pngfile")
            im = cv2.imread(file)
            if output_path:
                cv2.imwrite(os.path.join(output_path, name.replace('jpg', 'png')), im)
            else:
                cv2.imwrite(file.replace('jpg', 'png'), im)

if __name__ == '__main__':
    input_path = '/root/xinyuan/datasets/respng'
    output_path = '/root/xinyuan/datasets/RESISC45PNG'
    if not os.path.exists(input_path):
        print("文件夹不存在!")
    else:
        print("Start to transform!")
        transform(input_path, output_path)
        print("Transform end!")

5.查看文件夹大小或某个文件大小

5.1 du filepath:查看指定文件夹的大小(不指定默认为当前文件夹,且不递归显示子目录)

root@be7288f5053b:~/xinyuan/datasets/respng# du roundabout_525.jpg
16      roundabout_525.jpg

5.2 du -h filepath:以K 或M 或G人们更常见的方式展示大小

root@be7288f5053b:~/xinyuan/datasets/respng# du -h roundabout_525.jpg
16K     roundabout_525.jpg

6.查看文件夹下文件个数

6.1 查看某文件夹下文件的个数,包括子文件夹里的。

ls -lR|grep "^-"|wc -l

例如:

root@be7288f5053b:~/xinyuan/datasets/RESISC45PNG# ls -lR|grep "^-"|wc -l
31500

6.2 查看某文件夹下文件夹的个数,包括子文件夹里的

ls -lR|grep "^d"|wc -l

例如:

root@be7288f5053b:~/xinyuan/datasets# ls -lR|grep "^d"|wc -l
79

6.3 查看某种文件的个数(如jpg)

统计当前目录及所有子目录下以‘.jpg’后缀结尾的图片个数:

ls -lR | grep '.jpg' |wc -l

例如:

root@be7288f5053b:~/xinyuan/datasets# ls -lR|grep ".jpg"|wc -l
63001

7.数据集划分(抽取大约1/16的图像做测试集):

# -*- coding: utf-8 -*- 
# @Time : 2022/5/23 22:02 
# @File : drawTest.py 
# @RandomNumberSite:https://rand.91maths.com/ 随机生成数字网站
# @Function: 随机生成11-99中的6个数字为28 69 55 60 74 97,指定这些后缀.png的图片为测试图片,移动到测试文件夹下

import os
import shutil
import tqdm

def CreateDir(path):
    isExists=os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        os.makedirs(path) 
        print(path+' 目录创建成功')
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(path+' 目录已存在')

def drawFile(filepath, newPath):
    for root, dirs, files in os.walk(filepath, topdown=True):
        for file in files:
            if file.endswith("28.png") or file.endswith("69.png") or file.endswith("55.png") or file.endswith("60.png") or file.endswith("74.png") or file.endswith("97.png") : 
                shutil.move(os.path.join(root, file), os.path.join(newPath, file))      

if __name__ == "__main__":
    filepath = '/root/xinyuan/datasets/RESISC45PNG'
    # 创建目标文件夹
    newPath = '/root/xinyuan/datasets/RESISCtest'
    CreateDir(newPath)
    drawFile(filepath,newPath)

8.利用PIL库将多张图像排列组合成一张图像

import PIL.Image as Image
import os
 
IMAGES_PATH = '/root/xinyuan/datasets/testsetsaugment/' # 图片集地址
IMAGES_FORMAT = ['.png', '.JPG'] # 图片格式
IMAGE_SIZE = 256 # 每张小图片的大小
IMAGE_ROW = 2 # 图片间隔,也就是合并成一张图后,一共有几行
IMAGE_COLUMN = 4 # 图片间隔,也就是合并成一张图后,一共有几列
IMAGE_SAVE_PATH = '/root/xinyuan/datasets/birdaugmentall.png' # 图片转换后的地址
 
# 获取图片集地址下的所有图片名称
image_names = [name for name in os.listdir(IMAGES_PATH) for item in IMAGES_FORMAT if
               os.path.splitext(name)[1] == item]

#自定义排序方法:将flip_0_bird.png分为3段进行排序,避免python的默认sort排序导致含180的字符串排在带90的前
def func(info):
    names = info.split('_')
    return (names[0], int(names[1]), names[2])

#使用sort()将图片列表永久排序
image_names.sort( key = func)


# 简单的对于参数的设定和实际图片集的大小进行数量判断
if len(image_names) != IMAGE_ROW * IMAGE_COLUMN:
    raise ValueError("合成图片的参数和要求的数量不能匹配!")
    
# 定义拼接函数
def image_compose():
    to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_SIZE, IMAGE_ROW * IMAGE_SIZE)) #创建一个新图
    # 循环遍历,把每张图片按顺序粘贴到对应位置上
    for y in range(1, IMAGE_ROW + 1):
        for x in range(1, IMAGE_COLUMN + 1):
            from_image = Image.open(IMAGES_PATH + image_names[IMAGE_COLUMN * (y - 1) + x - 1]).resize(
                (IMAGE_SIZE, IMAGE_SIZE),Image.ANTIALIAS)
            to_image.paste(from_image, ((x - 1) * IMAGE_SIZE, (y - 1) * IMAGE_SIZE))
    return to_image.save(IMAGE_SAVE_PATH) # 保存新图
image_compose() #调用函数

9.将一个文件夹下的所有文件名排序后输出到一个txt文件

import os

path = '/root/xinyuan/datasets/RESISC45PNG/'         # 替换为你的文件夹路径
dir = os.listdir(path)                  # dir是目录下的全部文件
fopen = open('/root/xinyuan/datasets/list.txt', 'w') # 替换为你的文件名路径

#使用sort()将文件名列表永久排序
dir.sort()

for d in dir:           # d是每一个文件的文件名
    string = d + '\n'    #拼接字符串并换行
    fopen.write(string)             # 写入文件中
fopen.close()

10.zip把一个文件夹所有的文件压缩到一个压缩包

将 /home/html/ 这个目录下所有文件和文件夹打包为当前目录下的 html.zip:

zip -r html.zip /home/html

11.ln -s 创建软链接避免同一文件占用多个文件夹中的位置

将 datasets/GoPro 这个目录下所有文件和文件夹软链接到另一个目录下:
ln -s 原有文件绝对路径 准备建立链接到的路径
【!!!】如果是软链接文件,则链接路径后需要加上文件名

ln -s /root/Learning_degradation/datasets/GoPro /root/BasicSR/datasets/GoPro
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NewGe6

动力源泉:打赏+关注+点赞

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值