Python脚本——.csv文件转.txt脚本三则

第一则

"""
批量给指定文件夹内的所有.csv文件增加表头后转成txt
"""

import os

def add_header_and_convert_to_txt(csv_folder, header, output_folder):
    # 获取指定文件夹中的所有.csv文件
    csv_files = [f for f in os.listdir(csv_folder) if f.endswith('.csv')]

    # 遍历每个.csv文件
    for csv_file in csv_files:
        # 构造完整的文件路径
        csv_file_path = os.path.join(csv_folder, csv_file)

        # 构造.txt文件路径
        txt_file_name = os.path.splitext(csv_file)[0] + '.txt'
        txt_file_name = os.path.basename(txt_file_name)
        txt_file_path = os.path.join(output_folder, txt_file_name)

        # 在.csv文件的第一行之前插入表头,并将其保存为.txt文件
        with open(csv_file_path, 'r', encoding='utf-8') as csv_file:
            lines = csv_file.readlines()
            lines.insert(0, header + '\n')

            with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
                txt_file.writelines(lines)

    print('添加表头并转换为.txt文件完成。')

# 使用方法示例:
csv_folder_path = 'your_folder_path'  # 替换为包含多个.csv文件的文件夹路径
header = 'column1,column2,column3,column4,column5,column6,column7,column8,column9,column10,column11,column12,column13,column14,column15,column16,column17,column18,column19,column20'  # 替换为您的表头内容
output_folder_path = 'your_output_folder_path'  # 替换为转换后的文件输出路径

add_header_and_convert_to_txt(csv_folder_path, header, output_folder_path)

第二则

"""
给文件夹内特定的.csv文件添加表头后转成txt
"""
import os

def add_header_and_convert_to_txt(csv_folder, target_files, header):
    # 遍历目标文件夹中的文件
    for file_name in os.listdir(csv_folder):
        file_path = os.path.join(csv_folder, file_name)
        # 检查文件是否为目标 .csv 文件
        if file_name.endswith('.csv') and file_name in target_files:
            # 构造转换后的文件路径
            txt_file_path = os.path.splitext(file_path)[0] + '.txt'
            # 在 .csv 文件的第一行之前插入表头,并将其保存为 .txt 文件
            with open(file_path, 'r', encoding='utf-8') as csv_file:
                lines = csv_file.readlines()
                lines.insert(0, header + '\n')
                with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
                    txt_file.writelines(lines)

    print('添加表头并转换为 .txt 文件完成。')

# 使用方法示例:
csv_folder_path = 'your_folder_path'  # 替换为包含多个 .csv 文件的文件夹路径
target_csv_files = ['file1.csv', 'file2.csv']  # 替换为目标 .csv 文件名列表
header = 'column1,column2,column3,column4,column5'  # 替换为您的表头内容

add_header_and_convert_to_txt(csv_folder_path, target_csv_files, header)

第三则

"""
根据特定日期,在文件夹内获取特定的.csv文件添加表头后转成txt
"""
import os
import re
import datetime

def add_header_and_convert_to_txt(csv_folder, target_date, header):
    # 构造正则表达式模式
    pattern = re.compile(r'\d{8}\.csv$')

    # 遍历目标文件夹中的文件
    for file_name in os.listdir(csv_folder):
        if os.path.isfile(os.path.join(csv_folder, file_name)):
            # 检查文件名是否匹配正则表达式模式
            if pattern.match(file_name):
                # 提取文件名中的日期部分,并将其转换为 datetime 类型
                date_str = file_name.split('.')[0][-8:]
                file_date = datetime.datetime.strptime(date_str, '%Y%m%d').date()
                # 比较文件日期和目标日期
                if file_date == target_date:
                    # 如果日期匹配,在 .csv 文件的第一行之前插入表头,并将其保存为 .txt 文件
                    csv_file_path = os.path.join(csv_folder, file_name)
                    txt_file_path = os.path.splitext(csv_file_path)[0] + '.txt'
                    with open(csv_file_path, 'r', encoding='utf-8') as csv_file:
                        lines = csv_file.readlines()
                        lines.insert(0, header + '\n')
                        with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
                            txt_file.writelines(lines)
                    print(f'已处理文件:{file_name}')

    print('添加表头并转换为 .txt 文件完成。')

# 使用方法示例:
csv_folder_path = 'your_folder_path'  # 替换为包含多个 .csv 文件的文件夹路径
target_date_str = '20230101'  # 替换为您期望的日期字符串
header = 'column1,column2,column3,column4,column5'  # 替换为您的表头内容

target_date = datetime.datetime.strptime(target_date_str, '%Y%m%d').date()  # 将日期字符串转换为 datetime.date 类型
add_header_and_convert_to_txt(csv_folder_path, target_date, header)

for循环的两种不常见用法

for num in reversed(range(0, 31)):
    print(num)

for num in range(30, 0, -1):
    print(num)

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 你可以使用 Python 来实现将 .txt 文件内容化为 .csv 文件脚本。 以下是一个例子: ``` import csv # 读取 .txt 文件 with open('input.txt', 'r') as txt_file: lines = txt_file.readlines() # 将 .txt 文件内容化为列表 data = [] for line in lines: data.append(line.strip().split('@')) # 将列表内容写入 .csv 文件 with open('output.csv', 'w', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerows(data) ``` 在这个例子中,我们首先读取了 .txt 文件,然后使用 `strip()` 和 `split()` 函数将每行文本化为列表,最后使用 Python 的 `csv` 模块将列表内容写入 .csv 文件。 希望这对你有帮助。 ### 回答2: 文件换的脚本可以使用编程语言来实现,比如Python。下面是一个示例脚本: ```python import csv # 打开.txt文件 with open('input.txt', 'r') as input_file: txt_data = input_file.read().split('@') # 创建.csv文件并写入数据 with open('output.csv', 'w', newline='') as output_file: csv_writer = csv.writer(output_file) csv_writer.writerow(['数据']) # 标题行 # 逐行写入数据 for row in txt_data: csv_writer.writerow([row.strip()]) print("换完成!") ``` 脚本使用`csv`模块来读写.csv文件,首先使用`open`函数打开.txt文件,然后使用`read`方法读取文件内容,并使用`split('@')`将内容按照@符号进行分割,得到一个包含每行数据的列表。 然后,使用`open`函数创建.csv文件,指定文件名称为`output.csv`,并使用`csv.writer`创建一个写入器。使用`writerow`方法写入csv文件的标题行(这里以"数据"为例),然后使用一个循环逐行写入数据到csv文件中,每行数据通过`writerow`方法写入。 最后输出提示信息,表示换完成。 请注意,上述脚本中的`input.txt`是输入的.txt文件名,`output.csv`是换后的.csv文件名,请根据实际情况修改这两个文件名。 ### 回答3: 要将.txt文件内容化为.csv文件,可以编写一个脚本来实现。以下是一个简单的示例脚本: ```python import csv def convert_to_csv(txt_file, csv_file): with open(txt_file, 'r') as file: lines = file.readlines() # 去除换行符,并以@符号分割每一行 lines = [line.strip().split('@') for line in lines] with open(csv_file, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(lines) print('化完成') # 调用脚本的示例 txt_file = 'input.txt' # 输入的.txt文件 csv_file = 'output.csv' # 输出的.csv文件 convert_to_csv(txt_file, csv_file) ``` 以上脚本通过`open`函数打开.txt文件,并使用`readlines`方法读取所有行的内容。然后,将每一行的内容使用`strip`函数去除换行符,再使用`split`方法以@符号分割字符串。 接着,使用`open`函数以写入模式打开.csv文件,并使用`csv.writer`来创建一个写入器。最后,使用`writerows`方法将处理后的行列表写入.csv文件。 这个脚本可以将.txt文件的内容化为.csv文件。如果你需要使用其他文件名,只需修改`txt_file`和`csv_file`变量的值即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

今晚务必早点睡

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值