Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a string to a file goes to the wrong spot

I have a python script that takes a csv file and adds a string to it. The only issue is the string that I add is at the end of the string. I would like it to be in the front of the string instead of the end.

Here is the script:

#Adding string to the front of each line for the Part Numbers
string_to_add = r"V:\DATABASES\0 Suspension\Suspensia Pictures\ "

#Open the file and join the .JPG to the current lines
with open("PartNumbers.csv", 'r') as f:
    file_lines = [''.join([x.strip(), string_to_add,'\n']) for x in f.readlines()]

with open("PartNumbers.csv", 'w') as f:
    f.writelines(file_lines)

It gives me this output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

X00TB0001V:\DATABASES\0 Suspension\Suspensia Pictures\ 
X01BJ0003V:\DATABASES\0 Suspension\Suspensia Pictures\ 
X01BJ0004V:\DATABASES\0 Suspension\Suspensia Pictures\ 
X01BJ0005V:\DATABASES\0 Suspension\Suspensia Pictures\ 
X01BJ0006V:\DATABASES\0 Suspension\Suspensia Pictures\ 
X01BJ0007V:\DATABASES\0 Suspension\Suspensia Pictures\ 
X01BJ0008V:\DATABASES\0 Suspension\Suspensia Pictures\ 

This is the output I am looking for:

V:\DATABASES\0 Suspension\Suspensia Pictures\ X00TB0001
V:\DATABASES\0 Suspension\Suspensia Pictures\ X01BJ0003
V:\DATABASES\0 Suspension\Suspensia Pictures\ X01BJ0004
V:\DATABASES\0 Suspension\Suspensia Pictures\ X01BJ0005
V:\DATABASES\0 Suspension\Suspensia Pictures\ X01BJ0006
V:\DATABASES\0 Suspension\Suspensia Pictures\ X01BJ0007
V:\DATABASES\0 Suspension\Suspensia Pictures\ X01BJ0008

My original idea was to change around the line

file_lines = [''.join([x.strip(), string_to_add,'\n']) for x in f.readlines()]

to this:

file_lines = [ string_to_add,''.join([x.strip(),'\n']) for x in f.readlines()]

When I do that I get this error:

file_lines = [string_to_add,''.join([x.strip(), '\n']) for x in f.readlines()]
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: did you forget parentheses around the comprehension target?

How can I edit this script to get the desired output?

>Solution :

You need to switch the x.strip and the string_to_add:

file_lines = [''.join([string_to_add, x.strip(),'\n']) for x in f.readlines()]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading