python中,将txt文件转换为csv文件的几种方法

假设有一个文本文件 data.txt 内容如下:

Name, Age, City
John, 25, New York
Alice, 30, San Francisco
Bob, 28, Los Angeles

方法一、使用内置的 csv 模块:

import csv

# 读取txt文件
txt_file_path = 'data.txt'
csv_file_path = 'data.csv'

with open(txt_file_path, 'r') as txt_file, open(csv_file_path, 'w', newline='') as csv_file:
    # 创建CSV写入器
    csv_writer = csv.writer(csv_file)

    # 使用CSV读取器逐行读取txt文件
    csv_reader = csv.reader(txt_file)

    # 将每一行的内容写入CSV文件
    for row in csv_reader:
        csv_writer.writerow(row)

print(f"Successfully converted {txt_file_path} to {csv_file_path}.")

        这个例子中,csv.reader用于逐行读取txt文件的内容,然后将其写入csv文件中,使用csv.writer。请注意,newline=' ' 参数用于避免在写入csv文件时产生额外的空行。

方法二、使用 pandas 库:

import pandas as pd

# 读取txt文件
txt_file_path = 'data.txt'
csv_file_path = 'data.csv'

# 使用pandas读取txt文件
df = pd.read_csv(txt_file_path, delimiter=', ')

# 将数据写入csv文件
df.to_csv(csv_file_path, index=False)

print(f"Successfully converted {txt_file_path} to {csv_file_path}.")

        在这个例子中,pd.read_csv 函数用于读取txt文件,delimiter=', '  参数指定了逗号和空格作为分隔符。然后,df.to_csv 函数将数据写入csv文件。index=False 参数用于禁用写入文件时生成的索引列。

方法三、使用标准的文件读写操作

# 读取txt文件
txt_file_path = 'data.txt'
csv_file_path = 'data.csv'

with open(txt_file_path, 'r') as txt_file, open(csv_file_path, 'w', newline='') as csv_file:
    # 逐行读取txt文件
    for line in txt_file:
        # 假设txt文件中的字段是由逗号和空格分隔的
        fields = line.strip().split(', ')
        # 将字段以逗号分隔写入csv文件
        csv_file.write(','.join(fields) + 'n')

print(f"Successfully converted {txt_file_path} to {csv_file_path}.")

        这个例子中,使用 open 函数打开txt和csv文件,逐行读取txt文件,然后将每一行的字段以逗号分隔写入csv文件。需要根据实际情况进行字段的分隔和处理。虽然这种方法相对于使用 csv 模块和 pandas 库来说更为基础,但在某些简单的情况下,可能是一种直接且有效的方式。
        总体而言,使用 csv 模块和 pandas 库通常更为方便和灵活,尤其是在处理大型和复杂的数据集时。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>