简体   繁体   English

如何将所有 txt 文件从目录转换为 csv(创建和写入文件)并使用 Python 保存它们?

[英]How to convert all the txt file from a dir to csv's (creating and writing to file )and save them using Python?

convert all txt files delimiter '|'转换所有 txt 文件分隔符 '|' from dir path and convert to csv and save in a location using python?从目录路径转换为 ​​csv 并使用 python 保存在一个位置?

i have tried this code which is hardcoded.我试过这个硬编码的代码。

import csv

txt_file = r"SentiWS_v1.8c_Positive.txt"
csv_file = r"NewProcessedDoc.csv"

with open(txt_file, "r") as in_text:
    in_reader = csv.reader(in_text, delimiter = '|')
    with open(csv_file, "w") as out_csv:
        out_writer = csv.writer(out_csv, newline='')
        for row in in_reader:
            out_writer.writerow(row)

Expecting csv files with same file names in dir path for all txt files in path location对于路径位置中的所有 txt 文件,在 dir 路径中需要具有相同文件名的 csv 文件

pathlib provides most of the file handling stuff for you: pathlib为您提供了大部分文件处理内容:

import csv, pathlib

for path in pathlib.Path(".").glob("*.txt"):
    with path.open() as txtfile, path.with_suffix(".csv").open(mode="w") as csvfile:
        reader = csv.reader(txtfile, delimiter = '|')
        writer = csv.writer(csvfile)
        for row in reader:
            writer.writerow(row)

TO avoid blanks in the output file just added newline parameter in the above code import csv, pathlib为了避免输出文件中的空白,在上面的代码中添加了换行符参数 import csv, pathlib

for path in pathlib.Path(".").glob("*.txt"):
    with path.open() as txtfile, path.with_suffix(".csv").open(mode="w",**newline=''**) as csvfile:
        reader = csv.reader(txtfile, delimiter = '|')
        writer = csv.writer(csvfile)
        for row in reader:
            writer.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python将csv转换为txt文件? - How to convert csv to txt file using python? 如何使用 pyspark 将 csv 文件转换或保存为 txt 文件 - how to convert or save a csv file into a txt file using pyspark 使用 python 将 .txt 文件转换为 .csv 文件 - convert .txt file to .csv file using python 如何从表中获取所有列并将其保存为python中的csv文件在s3中 - How to fetch all columns from table and save it in s3 as csv file using python 如何使用 Python 将制表符 delimited.txt 文件转换为 xml 或 csv - How to convert a tab delimited .txt file to an xml or csv using Python 如何从csv读取没有标题的列并使用Python将输出保存在txt文件中? - How to read a column without header from csv and save the output in a txt file using Python? Python不创建文件(csv或txt) - Python not creating a file(csv or txt) Python 请求:从一个 TXT 文件中获取所有行,一次获取一个请求并将它们保存到一个新的 TXT 文件中 - Python Requests: take all lines from a TXT file, one at a time to get requests from each and save them to a new TXT file 如何使用 Glue 作业将 JSON 从 s3 转换为 CSV 文件并将其保存在同一个 s3 存储桶中 - How to convert JSON to CSV file from s3 and save it in same s3 bucket using Glue job 在python中创建和写入CSV文件 - creating and writing to a CSV file in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM