【问题标题】:Is there a way to get all cells with the same value from a spreadsheet?有没有办法从电子表格中获取所有具有相同值的单元格?
【发布时间】:2021-08-09 08:43:05
【问题描述】:

我在下面提供了一个示例,其中我在 column B 中有多个相同值,并假设 column A 中的字母是存在于此 Excel 工作表所在目录中的文件。

所以我想创建一个 Python 脚本,例如,将查看具有相同值的列,比如4,并创建一个名为4 的目录,并放置所有对应的文件与column A 相同的值4,在那个文件中!所以最终结果将是一个名为4 的目录,其中包含文件DKL

Column A    Column B
A           1
B           2
C           3
D           4
E           3
F           3
G           1
K           4
L           4

【问题讨论】:

  • 嘿@scape7575!你的工作表是什么类型的?
  • 嗨 @VidyaGanesh 我的工作表是 .tsv,但我也有一个 .csv 副本,谢谢!!
  • 对不起!我正在尝试代码,同时替换“df”和“directory”的目录,但它似乎不起作用,第 8 行错误“KeyError:'ColB'”,谢谢
  • 在我使用 ColA 和 ColB 的情况下检查 ColumnA 和 ColumnB 的名称
  • 我假设文件 A B C 的扩展名是 .txt,我在第 10 行用作扩展名

标签: python excel pandas dataframe file


【解决方案1】:

您可以使用pandas 来执行此操作。这是我尝试使用 .txt 文件的示例,这些文件根据 column2 值传输到其相应的文件夹 1 2 等。

import pandas as pd
import os
import shutil
directory= r"C:\Use\your\parent\directory\where\all\the\files\exist"
df=pd.read_csv("csv.csv")

for index, row in df.iterrows():
    new_folder=os.path.join(directory,str(row['ColB']))
    os.makedirs(new_folder,exist_ok=True) #creates a new dir if folder with that particular number from ColB as name doesnot exist
    source=os.path.join(directory,str(row['ColA']+'.txt'))
    destination =os.path.join(directory,str(row['ColB']))
    # Move the file from source to destination based on the dataframe's ColA and ColB
    if os.path.isfile(source): 
        dest = shutil.move(source, destination) 
    else: 
        continue
    

这样做是将ColA 文件从父目录移动到使用ColB 值创建的相应文件夹

Folders | Files
1        -A
         -G
------------
2        -B
------------
3        -C
         -E
         -F

【讨论】:

  • 这个输出示例正是我想要达到的,完美。
  • 我添加了一个循环来检查来自 ColA 的文件是否存在(我需要它以供我使用),如果有人需要它:if os.path.isfile(source): dest = shutil.move(源,目的地)否则:继续
  • 很好的发现。谢谢@scape7575
【解决方案2】:

您可以使用 os 模块来创建目录和移动文件。你说你有一个电子表格,但我认为它是某种文本格式?那么下面的代码应该可以工作了:

#!/usr/bin/python
import os
#Open data-file for reading
my_sheet = open('path/to/files/sheet.txt', 'r')
#Skip the header in data-file
my_sheet.readline()
#Read data-file line-by-line
for line in my_sheet:
    #Split line on white-space, directory is element[1]
    my_dir = 'path/to/files/'+line.split()[1]
    #Create directory if it does not exist
    if not os.path.exists(my_dir):
        os.mkdir(my_dir)
    #Split line on white-space, file is element[0], move file to dir 
    os.rename('path/to/files/'+line.split()[0], my_dir+'/'+line.split()[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多