Suppose there is a text file with the following content:
Name, Age, City John, 25, New York Alice, 30, San Francisco Bob, 28, Los Angeles
Method 1: Use the built-in csv module:
import csv # Read txt filetxt_file_path = '' csv_file_path = '' with open(txt_file_path, 'r') as txt_file, open(csv_file_path, 'w', newline='') as csv_file: # Create a CSV writer csv_writer = (csv_file) # Use CSV reader to read txt files line by line csv_reader = (txt_file) # Write the content of each line to the CSV file for row in csv_reader: csv_writer.writerow(row) print(f"Successfully converted {txt_file_path} to {csv_file_path}.")
In this example, it is used to read the contents of the txt file line by line, and then write it to the csv file, and use it. Note that the newline=' ' parameter is used to avoid additional blank lines when writing to the csv file.
Method 2: Use the pandas library:
import pandas as pd # Read txt filetxt_file_path = '' csv_file_path = '' # Use pandas to read txt filesdf = pd.read_csv(txt_file_path, delimiter=', ') # Write data to csv filedf.to_csv(csv_file_path, index=False) print(f"Successfully converted {txt_file_path} to {csv_file_path}.")
In this example, the pd.read_csv function is used to read the txt file, and the delimiter=', ' parameter specifies commas and spaces as delimiters. The df.to_csv function then writes the data to the csv file. The index=False parameter is used to disable the index column generated when writing to a file.
Method 3: Use standard file read and write operations
# Read txt filetxt_file_path = '' csv_file_path = '' with open(txt_file_path, 'r') as txt_file, open(csv_file_path, 'w', newline='') as csv_file: # Read txt file line by line for line in txt_file: # Assume that the fields in the txt file are separated by commas and spaces fields = ().split(', ') # Write fields to csv file separated by commas csv_file.write(','.join(fields) + '\n') print(f"Successfully converted {txt_file_path} to {csv_file_path}.")
In this example, use the open function to open the txt and csv files, read the txt file line by line, and then write the fields of each line to the csv file separated by commas. Fields need to be separated and processed according to actual conditions. While this approach is more basic than using the csv module and pandas library, in some simple cases, it may be a straightforward and efficient way.
Overall, using the csv module and pandas library is often more convenient and flexible, especially when dealing with large and complex datasets.
Attachment: Python implements the merge of multiple .txt text data into .csv file data
import os import csv def file_name(file_dir): for root, dirs, files in (file_dir): #root returns the current directory path; dirs returns all subdirectories under the current path; files returns all non-directories subfiles under the current path return root,dirs,files fieldnames=['review','class'] if __name__=='__main__': csv_file=open("./",'a+',newline='',encoding='utf-8') writer=(csv_file,fieldnames=fieldnames) () 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+= () ({'review':data,'class':dir_0}) csv_file.close()
Summarize
This is the end of this article about three methods of converting txt files into csv files in python. For more related python to convert txt files into csv files, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!