首页 > 其他分享 >合并所有文件

合并所有文件

时间:2024-09-14 16:37:35浏览次数:1  
标签:文件 df 所有 合并 cell file path os row

import os
import pandas as pd
import os
import shutil

def clear_folder(folder_path):
# 检查文件夹是否存在
if not os.path.exists(folder_path):
print(f"文件夹 {folder_path} 不存在。")
return

# 遍历文件夹中的所有文件和子文件夹
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)

try:
# 如果是文件,删除文件
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
# 如果是文件夹,删除文件夹及其内容
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(f'删除 {file_path} 时出错: {e}')

print(f"文件夹 {folder_path} 已清空。")

# 指定要清空的文件夹路径
folder_path = './folder'

# 调用函数清空文件夹
clear_folder(folder_path)
def find_sn_row(df):
for i, row in df.iterrows():
if any('SN' in str(cell) for cell in row):
return i
if any('条码' in str(cell) for cell in row):
return i
return None

def read_file_with_fallback(file_path, file_type):
encodings = ['utf-8', 'gb18030']
for encoding in encodings:
try:
if file_type == 'csv':
return pd.read_csv(file_path, header=None, encoding=encoding)
elif file_type == 'xls':
return pd.read_excel(file_path, engine='xlrd', header=None)
elif file_type == 'xlsx':
return pd.read_excel(file_path, engine='openpyxl', header=None)
except (UnicodeDecodeError, ValueError):
continue
raise ValueError(f"Failed to read {file_path} with available encodings")

def convert_to_xlsx(source_directory, target_directory):
# 如果目标目录不存在,则创建它
if not os.path.exists(target_directory):
os.makedirs(target_directory)

# 遍历源目录及其所有子目录下的所有文件
for root, dirs, files in os.walk(source_directory):
for filename in files:
file_path = os.path.join(root, filename)

# 检查文件扩展名并进行相应处理
if filename.endswith('.csv'):
df = read_file_with_fallback(file_path, 'csv')
new_filename = filename.replace('.csv', '.xlsx')
elif filename.endswith('.xls'):
df = read_file_with_fallback(file_path, 'xls')
new_filename = filename.replace('.xls', '.xlsx')
elif filename.endswith('.xlsx'):
df = read_file_with_fallback(file_path, 'xlsx')
new_filename = filename # 保持原来的文件名
else:
continue

# 找到包含 "SN" 的行并设置为新的索引行
sn_row_index = find_sn_row(df)
if sn_row_index is not None:
new_header = df.iloc[sn_row_index]
df.columns = new_header
df = df.drop(index=sn_row_index).reset_index(drop=True)

# 保存为新的 xlsx 文件到目标目录
relative_path = os.path.relpath(root, source_directory)
new_file_dir = os.path.join(target_directory, relative_path)
if not os.path.exists(new_file_dir):
os.makedirs(new_file_dir)
new_file_path = os.path.join(new_file_dir, new_filename)
df.to_excel(new_file_path, index=False)
print(f"Converted {file_path} to {new_file_path}")

# 使用示例
source_directory = './root' # 替换为你的源目录路径
target_directory = './folder' # 替换为你的目标目录路径
convert_to_xlsx(source_directory, target_directory)
def get_all_excel_files(directory):
excel_files = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.xlsx') :
excel_files.append(os.path.join(root, file))
return excel_files
# 读取 CSV 文件

root_directory = './folder'
file_paths = get_all_excel_files(root_directory)
print(file_paths)
dataframes = []
for file_path in file_paths:
df = pd.read_excel(file_path) # 根据需要指定编码
dataframes.append(df)


# 读取第二个文件

concatenated_df = pd.concat(dataframes, axis=0, ignore_index=True)
def find_limits_and_data(df):
# 初始化变量
up_row, low_row = None, None
up_col, low_col = None, None

# 遍历DataFrame以找到包含"上限"或"UP"的单元格(从后往前)
for row in range(df.shape[0] - 1, -1, -1):
for col in range(df.shape[1] - 1, -1, -1):
cell_value = str(df.iat[row, col]).strip().lower()
if up_row is None and ("up" in cell_value or "上限" in cell_value or "usp" in cell_value):
up_row, up_col = row, col
if low_row is None and ("low" in cell_value or "下限" in cell_value or "lsp" in cell_value):
low_row, low_col = row, col

if up_row!=None and low_row!=None:
break

# 如果找到了上限和下限行,将它们移动到最前面
if up_row is not None and low_row is not None:
# 获取上限和下限行
up_limit_row = df.iloc[up_row]
low_limit_row = df.iloc[low_row]

# 删除原来的上限和下限行
df = df.drop([up_row, low_row])

# 将上限和下限行插入到最前面
df = pd.concat([pd.DataFrame([up_limit_row]), pd.DataFrame([low_limit_row]), df.reset_index(drop=True)], ignore_index=True)

return df
concatenated_df = find_limits_and_data(concatenated_df)
import pandas as pd

def clean_dataframe(df):
# 找到包含 "SN" 或 "条码" 的列索引
sn_barcode_cols = []

for col in df.columns:
if 'sn' in col.lower() or '条码' in col.lower():
sn_barcode_cols.append(col)

# 如果没有找到相关列,直接返回原始 DataFrame
if not sn_barcode_cols:
return df

# 从第三行(包括第三行)开始遍历 DataFrame
rows_to_drop = []
for row in range(2, df.shape[0]):
for col in sn_barcode_cols:
cell_value = df.at[row, col]

# 检查单元格是否为空或长度小于4
cell_invalid = (pd.isna(cell_value) or cell_value == '' or len(str(cell_value)) < 4)

# 如果单元格无效,则记录该行索引并跳出内层循环
if cell_invalid:
rows_to_drop.append(row)
break

# 删除记录的行
df = df.drop(rows_to_drop).reset_index(drop=True)

return df

concatenated_df1 = clean_dataframe(concatenated_df)
concatenated_df1.to_excel('merged_output.xlsx', index=False, engine='xlsxwriter')

标签:文件,df,所有,合并,cell,file,path,os,row
From: https://www.cnblogs.com/lfh123123/p/18414277

相关文章

  • Python存储与读写二进制文件
    本文介绍了一种在Python中将Numpy数组转存为一个紧凑的二进制格式的文件,及其使用内存映射的形式进行读取的方案。一个二进制的数据流,不仅可以更加方便页形式的内存映射,相比于传统的Numpy单精度浮点数数组还有一个可哈希的特性。总体来说是一个对于高性能计算十分友好的存......
  • GGUF大模型文件格式
    GGUF大模型文件格式https://www.datalearner.com/blog/1051705718835586 大语言模型的开发通常使用PyTorch等框架,其预训练结果通常也会保存为相应的二进制格式,如pt后缀的文件通常就是PyTorch框架保存的二进制预训练结果。但是,大模型的存储一个很重要的问题是它的模型文件巨......
  • 实现 Excel 文件导入到向量数据库(Milvus),并支持 先查询知识库(Milvus),然后再查询大模型(Ol
    为了实现Excel文件导入到向量数据库(Milvus),并支持先查询知识库(Milvus),然后再查询大模型(Ollama)的功能,以下是具体的实现步骤:1.导入Excel数据到向量数据库(Milvus)首先,您需要将Excel文件中的数据向量化,并将这些向量导入到Milvus数据库中。可以使用pandas读取Excel文件,使用......
  • src/pyaudio/device_api.c:9:10: fatal error: portaudio.h: 没有那个文件或目录
    (venv)shgbitai@shgbitai-C9X299-PGF:~/pythonworkspace/ai-accompany$pipinstallpyaudiosounddeviceCollectingpyaudioDownloadingPyAudio-0.2.14.tar.gz(47kB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━47.1/47.1k......
  • LeetCode56. 合并区间(2024秋季每日一题 16)
    以数组intervals表示若干个区间的集合,其中单个区间为intervals[i]=[starti,endi]。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。示例1:输入:intervals=[[1,3],[2,6],[8,10],[15,18]]输出:[[1,6],[8,10],[15,18]]解释:区间[1,3]......
  • 10款功能强大的电脑加密软件排行榜!企业文件加密软件推荐
    在当今数字化时代,数据安全已成为企业运营的重中之重。无论是个人用户还是企业用户,都需要确保其重要文件和数据的安全性。电脑加密软件作为一种有效的数据保护工具,能够帮助用户加密敏感信息,防止数据泄露和未经授权的访问。1.安秉网盾这是一款专门为满足企业需求设计的加密软......
  • python https 下载文件
    同步下载defdownload_file_block(url:str,file_path:str):logging.basicConfig(level=logging.DEBUG)log=logging.getLogger('requests.packages.urllib3')log.setLevel(logging.DEBUG)log.propagate=TrueclassDebugAdapter(HTTPAd......
  • 无数据备份和无归档文件时,使用bbed修改数据文件头的SCN,强制打开数据库的方法
    在数据库运维中经常会遇到某个数据文件的SCN与其他文件的SCN不一致(如offline后或者异常断电),如果归档日志被删除了,导致datafile不能recover,数据库不能打开情况,这时候我们需要借助bbed修改datafileheader的scn与其他datafile的headerscn一致,然后recoverdatafile。一、问题产生......
  • 如何在局域网中(学校机房)实现文件共享(机位共享文件夹可被其他机位访问)
    操作环境:学校机房,win7(旗舰版)操作系统(无需担心电脑问题,机房电脑重启后即可恢复默认设置)。流程:1,创建你需要共享的文件夹。在D盘创建share文件夹。D:\share2,右键share文件夹点击属性找到共享页面,点击共享,添加Everyone用户,可修改其对文件夹的访问权限。2.1,在share属性......
  • 四个方法,加密文件\文件夹
    在数字化时代,数据安全已成为企业和个人不可忽视的重要议题。加密作为保护敏感信息免受未授权访问的有效手段,其重要性日益凸显。本文将深入探讨加密文件与文件夹的四大高效方法,帮助大家构建更加坚固的数据防护屏障。方法一:首先,有很多文件都是自带加密方式的,比如pdf、word、exc......