最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中將txt文件轉(zhuǎn)換為csv文件的三種方法舉例

 更新時間:2024年06月17日 09:47:26   作者:阿羅的小小倉庫  
對于大數(shù)據(jù)的處理基本都是以CSV文件為基礎(chǔ)進(jìn)行的,那么在進(jìn)行深度學(xué)習(xí)的處理之前,需要先統(tǒng)一數(shù)據(jù)文件的格式,下面這篇文章主要給大家介紹了關(guān)于python中將txt文件轉(zhuǎn)換為csv文件的三種方法,需要的朋友可以參考下

假設(shè)有一個文本文件 data.txt 內(nèi)容如下:

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

方法一、使用內(nèi)置的 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:
    # 創(chuàng)建CSV寫入器
    csv_writer = csv.writer(csv_file)

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

    # 將每一行的內(nèi)容寫入CSV文件
    for row in csv_reader:
        csv_writer.writerow(row)

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

這個例子中,csv.reader用于逐行讀取txt文件的內(nèi)容,然后將其寫入csv文件中,使用csv.writer。請注意,newline=' ' 參數(shù)用于避免在寫入csv文件時產(chǎn)生額外的空行。

方法二、使用 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=', ')

# 將數(shù)據(jù)寫入csv文件
df.to_csv(csv_file_path, index=False)

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

在這個例子中,pd.read_csv 函數(shù)用于讀取txt文件,delimiter=', '  參數(shù)指定了逗號和空格作為分隔符。然后,df.to_csv 函數(shù)將數(shù)據(jù)寫入csv文件。index=False 參數(shù)用于禁用寫入文件時生成的索引列。

方法三、使用標(biāo)準(zhǔn)的文件讀寫操作

# 讀取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:
        # 假設(shè)txt文件中的字段是由逗號和空格分隔的
        fields = line.strip().split(', ')
        # 將字段以逗號分隔寫入csv文件
        csv_file.write(','.join(fields) + '\n')

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

這個例子中,使用 open 函數(shù)打開txt和csv文件,逐行讀取txt文件,然后將每一行的字段以逗號分隔寫入csv文件。需要根據(jù)實(shí)際情況進(jìn)行字段的分隔和處理。雖然這種方法相對于使用 csv 模塊和 pandas 庫來說更為基礎(chǔ),但在某些簡單的情況下,可能是一種直接且有效的方式。

總體而言,使用 csv 模塊和 pandas 庫通常更為方便和靈活,尤其是在處理大型和復(fù)雜的數(shù)據(jù)集時。

附:Python實(shí)現(xiàn)多條.txt文本數(shù)據(jù)合并為.csv文件數(shù)據(jù)

import os
import csv
 
def file_name(file_dir):  
    for root, dirs, files in os.walk(file_dir):   
    #root返回當(dāng)前目錄路徑;dirs返回當(dāng)前路徑下所有子目錄;files返回當(dāng)前路徑下所有非目錄子文件
        return root,dirs,files
 
fieldnames=['review','class']
 
if __name__=='__main__':
 
    csv_file=open("./merge.csv",'a+',newline='',encoding='utf-8')
    writer=csv.DictWriter(csv_file,fieldnames=fieldnames)
    writer.writeheader()
 
    file_dir = "E:/SmartTravelling/Code_bert_zhihu/THUCNews/THUCNews"
 
    root_0,dirs_0,_ = file_name(file_dir)
    
    for dir_0 in dirs_0:
        curdir=root_0+'/'+dir_0
        root_1,_,files= file_name(curdir)
 
        for line in files:
            line=root_1+'/'+line
            data=''
            for temp in open(line, 'r',encoding="utf-8").readlines():
                if temp !='/n':
                    data+= temp.strip() 
            
            writer.writerow({'review':data,'class':dir_0})
 
    csv_file.close()

總結(jié)

到此這篇關(guān)于python中將txt文件轉(zhuǎn)換為csv文件的三種方法的文章就介紹到這了,更多相關(guān)python將txt文件轉(zhuǎn)換csv文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

邹平县| 华亭县| 威信县| 黄梅县| 洛川县| 通州区| 曲阜市| 壶关县| 敦化市| 阿克苏市| 博乐市| 哈巴河县| 田阳县| 卢龙县| 泗水县| 灵寿县| 泰顺县| 高清| 许昌县| 林周县| 章丘市| 时尚| 喀喇沁旗| 宣威市| 东乡| 偏关县| 嘉善县| 平湖市| 滦平县| 台湾省| 达拉特旗| 同仁县| 临安市| 泗水县| 太康县| 河源市| 乌恰县| 遵化市| 新绛县| 宜川县| 文昌市|