python .txt文件奇数偶数行分开保存

Python脚本:文件按行拆分并分别写入奇偶文件
这段代码展示了如何使用Python将一个文本文件的行按奇偶数行分开,将偶数行写入一个文件,奇数行写入另一个文件,适用于数据预处理或简单的文本操作。
部署运行你感兴趣的模型镜像
def fenhang(infile,outfile,outfile1):
 
 infopen = open(infile,'r',encoding='utf-8')
 outopen = open(outfile,'w',encoding='utf-8')
 outopen1 = open(outfile1, 'w', encoding='utf-8')
 lines = infopen.readlines()
 i = 0
 for line in lines:
  i += 1
  if i % 2 == 0:
      outopen.write(line)
  else:
      outopen1.write(line)

 infopen.close()
 outopen.close()

if __name__=="__main__":
    infile='/Wnt/Wnt_proteinB.txt'
    outfile='/Wnt/Wnt_proteinBBBB.txt'  ####偶数行
    outfile1='/Wnt_proteinnameB.txt'    ####奇数行
    
    fenhang(infile,outfile,outfile1)

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

import os from docx import Document import pandas as pd def extract_table_texts(docx_path, max_rows=30): """提取单个docx文件所有表格的前max_rows文本""" doc = Document(docx_path) file_texts = [] # 存储当前文件所有表格的前30文本 for table in doc.tables: table_texts = [] # 遍历表格的每一,最多取max_rows for row_idx, row in enumerate(table.rows): if row_idx >= max_rows: break # 超过30时停止 row_text = [] for cell in row.cells: text = cell.text.strip() if text: row_text.append(text) # 合并当前的单元格文本(用逗号分隔) table_texts.append(", ".join(row_text)) # 合并当前表格的文本(用分号分隔不同) file_texts.append("; ".join(table_texts)) # 合并所有表格的文本(用换符分隔不同表格) return "\n".join(file_texts) def process_folder(folder_path, output_file="output.xlsx"): """处理文件夹中所有docx文件,每个文件占Excel一""" data = [] # 遍历文件夹 for filename in os.listdir(folder_path): if filename.lower().endswith(".docx"): file_path = os.path.join(folder_path, filename) try: # 提取文本并添加到数据列表 combined_text = extract_table_texts(file_path) data.append({"文件名": filename, "表格内容(前30)": combined_text}) except Exception as e: print(f"处理文件 {filename} 时出错: {str(e)}") # 创建DataFrame df = pd.DataFrame(data) # 保存结果(无需去重) df.to_excel(output_file, index=False) return df # 使用示例 if __name__ == "__main__": input_folder = "/path/to/your/documents" # 替换为实际路径 output_file = "extracted_texts.xlsx" result_df = process_folder(input_folder, output_file) print(f"完成!共处理 {len(result_df)} 个文件,已保存至 {output_file}")请改进代码,仅提取docx表格前42,并且在xlsx中将基数作一列排列,偶数作一列排列
03-14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值