How to use multiple delimiters when using csv.reader in python?

I have several lines of texts in a text file that looks something like this:

2012-03-16 13:47:30.465 -0400 START Running Lab.script 19 on_the 

I want this text file can be converted to csv. I already did this with this code:

 fin = csv.reader(open('LogFile.txt', 'rb'), delimiter='\t') fout = open('newLogFile.csv', 'w') for row in fin: fout.write(','.join(row) + '\n') 

But now my problem is that I need to add a "," after spaces in this part of the line:

 2012-03-16 13:47:30.465 -0400 

I'm not sure how to do this, I tried using split () to split the current line / position, but that didn't work. Any suggestions would be very helpful.

thanks

+6
source share
2 answers

Would it be useful instead to just drag and drop everything from the start? If so, you can refer to this answer , essentially

There is a special random label for this use case!

If you call str.split without an argument, it breaks into runs instead of spaces. So:

 >>> ' '.join("Please \n don't \t hurt \x0b me.".split()) "Please don't hurt me." 

so for you it will be

 newLogFile = open('newLogFile.csv', 'w') textFile = open('LogFile.txt', 'rb') for row in textFile: newLogFile.write('\t'.join(row.split())) 

Also you said

But now my problem is that I need to add a "," after spaces in this part of the line:

2012-03-16 13: 47: 30.465-0400

it seems to me that you want

 2012-03-16 ,13:47:30.465 ,-0400 
+3
source

Try the following:

 fin = csv.reader(open('LogFile.txt', 'rb'), delimiter='\t') fout = open('newLogFile.csv', 'w') for row in fin: row[0] = ','.join(row[0].split()) fout.write(','.join(row) + '\n') 

This will take a line that looks like this: csv.reader() :

 ['2012-03-16 13:47:30.465 -0400', 'START', 'Running', 'Lab.script', '19 ', 'on_the'] 

And then change the first element so that it looks like this:

 ['2012-03-16,13:47:30.465,-0400', 'START', 'Running', 'Lab.script', '19 ', 'on_the'] 

And after ','.join() in the line, you get a line that will be written to your output file:

 '2012-03-16,13:47:30.465,-0400,START,Running,Lab.script,19,on_the' 

If they have other elements that may contain spaces, and you want to treat them as a separator in the csv output, you can do the following:

 fin = csv.reader(open('LogFile.txt', 'rb'), delimiter='\t') fout = open('newLogFile.csv', 'w') for row in fin: fout.write(','.join(','.join(item.split()) for item in row) + '\n') 
+2
source

Source: https://habr.com/ru/post/910957/


All Articles