首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CSV文件将文件移动到不同的目录

使用CSV文件将文件移动到不同的目录
EN

Ask Ubuntu用户
提问于 2016-12-10 22:26:23
回答 1查看 2.4K关注 0票数 2

我有一个机器学习数据集中的大型1000+文件目录,但是这些文件有不同的质量(玫瑰图片与守护花图片,以保持简单)。我有这个CSV文件,其中包含数据集中每一项的文件名以及它们的分类(玫瑰对雏菊)。我如何读取这个CSV文件,并告诉我的文件管理器将所有玫瑰照片移至一个目录,将所有雏菊照片移至另一个目录?我是否需要使用Bash脚本,或者这是已经构建在Nautilus中的东西?

EN

回答 1

Ask Ubuntu用户

回答已采纳

发布于 2016-12-11 14:37:14

好吧,我和一个朋友用Python写了一个脚本,很好地解决了这个问题。

代码语言:javascript
复制
# Import csv
import csv
# Import os
import os

# Main Function
def main():
# Open dataset file
dataset = open('dataset.csv', newline='')

# Initialize csvreader for dataset
reader = csv.reader(dataset)

# Read data from reader
data = list(reader)

# Variables for progress counter
lines = len(data)
i = 0

# Analyze data in dataset
for row in data:
    # Assign image name and state to variables
    image = row[0] + '.jpeg'
    state = row[1]

    # Print image information
    print('({}/{}) Processing image ({}): {}'.format(i + 1, lines, state, image))

    # Increment i
    i += 1

    # Determine action to perform
    if state is '0':
        # Attempt to move the file
        try:
            # Move the file to nosymptoms/
            os.rename(image, 'nosymptoms/' + image)
            # Inform the user of action being taken
            print(' -> Moved to nosymptoms/')
        except FileNotFoundError:
            # Inform the user of the failure
            print(' -> Failed to find file')
    elif state in ['1', '2', '3', '4']:
        # Attempt to move the file
        try:
            # Move the file to nosymptoms/
            os.rename(image, 'symptoms/' + image)
            # Inform the user of action being taken
            print(' -> Moved to symptoms/')
        except FileNotFoundError:
            # Inform the user of the failure
            print(' -> Failed to find file')

# Execute main function if name is equal to main
if __name__ == '__main__':
main()

这往往更好,因为我有更多的类别来处理with...hopefully,这将适用于任何有同样问题的人。

票数 0
EN
页面原文内容由Ask Ubuntu提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://askubuntu.com/questions/859275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档