Advertisement
Python253

txt2csv

Mar 15th, 2024
434
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: txt2csv.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a text file (.txt) to a CSV file (.csv).
  10. Assumes each line in the text file is a separate record in the CSV file.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'txt2csv.py'.
  17. 2. Ensure your text file ('example.txt') is in the same directory as the script.
  18. 3. Run the script.
  19. 4. The converted CSV file ('txt2csv.csv') will be generated in the same directory.
  20.  
  21. Note: Adjust the 'txt_filename' and 'csv_filename' variables in the script as needed.
  22. """
  23.  
  24. import csv
  25.  
  26. def txt_to_csv(txt_filename, csv_filename):
  27.     with open(txt_filename, 'r') as txtfile, open(csv_filename, 'w', newline='') as csvfile:
  28.         csvwriter = csv.writer(csvfile)
  29.         for line in txtfile:
  30.             # Assuming each line in the text file is a separate record
  31.             csvwriter.writerow([line.strip()])
  32.  
  33. if __name__ == "__main__":
  34.     # Set the filenames for the text and CSV files
  35.     txt_filename = 'example.txt'
  36.     csv_filename = 'txt2csv.csv'
  37.  
  38.     # Convert the text to a CSV file
  39.     txt_to_csv(txt_filename, csv_filename)
  40.  
  41.     print(f"Converted '{txt_filename}' to '{csv_filename}'.")
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement