简体   繁体   中英

How to convert TXT to CSV?

I need your help. I have a text file, which is a database. The data in it looks something like this:

Anastasia [ID: 257949614] requested statistics for Russia - (13:48:37, 17.03.2020)
Alina [ID: 541327376] requested statistics for Russia - (13:50:45, 17.03.2020)
Alina [ID: 541327376] requested statistics for USA - (13:51:10, 17.03.2020)
Alina [ID: 541327376] requested statistics for Egypt - (13:51:50, 17.03.2020)
lofi [ID: 605986150] requested statistics for Montenegro - (13:51:58, 17.03.2020)

I need to convert it to CSV, while putting different data types in separate cells. Something like this:

在此处输入图片说明

Step 1 - create a function that receives a text line and splits it to string however you like. There is not short way to do it because your original file is regular text. For instance:

def split_line(l):
  name = l[:l.find(' ')]
  l = l[len(name) + 1]
  id = l[:l.find(']')+1]
  l = l[len(id) + 1:]
  # ...
  return name, id, # ...

Step 2 - convert text file to list of lists (or tuples, in my case):

with open(input_file) as f:
  lines = [split_line(x) for x in f]

Step 3 - use the csv module.

import csv
with open(output_file, 'w') as f:
  writer = csv.writer(f)
  writer.writelines(lines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM