Entering edit mode
2.2 years ago
Paula
▴
60
Hi! I have a csv file and I need to format it. The input csv file looks like this:
old_name,new_name
"NODE_1_length_592822_cov_338.586386
", SOL_1_3_cov_338.586386_N_1
"NODE_1_length_592822_cov_338.586386
",SOL_1_3_cov_338.586386_N_2
And the final result should look like this:
old_name,new_name
NODE_1_length_592822_cov_338.586386, SOL_1_3_cov_338.586386_N_1
NODE_1_length_592822_cov_338.586386,SOL_1_3_cov_338.586386_N_2
I have tried multiple strategies but none of them has given the desired result:
with open('file.csv','r') as f:
content = f.readlines()
cleaned = ''
for line in content:
if line != '\n':
cleaned += line
print(cleaned.replace(" ",""))
Another one
text = open("file.csv", "r", encoding="utf8")
text = ''.join([i for i in text]) \
.replace(" ", "")
x = open("file1" + i + ".csv", "w", encoding="utf8")
x.writelines(text)
x.close()
And another one
import csv
with open('file.csv', newline='') as in_file:
with open('new_file.csv', 'w', newline='') as out_file:
writer = csv.writer('new_file.csv')
for row in csv.reader('file.csv'):
if row:
writer.writerow(row)
Do you have any ideas as to how to solve it?
Thanks!
It would be easier to read the whole file into memory.
Output:
Thanks Andrzej! I'd like to ask you one additional question if you don't mind. If I want to keep the spaces in words in the first column. For example:
I want to obtain
Instead of:
How can I modify the script?
Thanks a lot!
Could you show me the first few lines of the csv?
Sure!
Thanks!
Please do not add any
"
or other exraneous characters to data examples. Use the101010
button to format the data you want to show in proper format.Thanks GenoMax!