简体   繁体   中英

Python adding a string leaves extra characters

If you need any more info just Let Me Know

I have a python script that adds a string after each line on a CSV file. the line file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()] is the trouble maker. For each file line it will add the string and then add a new line after each time the string is added.

Here is the script:

#Adding .JPG string to the end of each line for the Part Numbers
string_to_add = ".JPG"

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

#Writes to the file until its done
with open("PartNums.csv", 'w') as f:
    f.writelines(file_lines)

The script works and does what it is supposed to, however my issue is later on in this larger script. This script outputs into a CSV file and it looks like this:

X00TB0001.JPG
X01BJ0003.JPG
X01BJ0004.JPG
X01BJ0005.JPG
X01BJ0006.JPG
X01BJ0007.JPG
X01BJ0008.JPG
X01BJ0026.JPG
X01BJ0038.JPG
X01BJ0039.JPG
X01BJ0040.JPG
X01BJ0041.JPG
...
X01BJ0050.JPG
X01BJ0058.JPG
X01BJ0059.JPG
X01BJ0060.JPG
X01BJ0061.JPG
X01BJ0170.JPG
X01BJ0178.JPG

Without the \n in that line the csv file output looks like this file_lines = [''.join([x.strip(), string_to_add]) for x in f.readlines()] :

X00TB0001.JPGX01BJ0003.JPGX01BJ0004.JPGX01BJ0005.JPGX01BJ0006.JPG

The issue is when I go to read this file later and move files with it using this script:

#If the string matches a file name move it to a new directory
dst = r"xxx"

with open('PicsWeHave.txt') as my_file:
    for filename in my_file:
        src = os.path.join(XXX") # .strip() to avoid un-wanted white spaces
        #shutil.copy(src, os.path.join(dst, filename.strip()))
        shutil.copy(os.path.join(src, filename), os.path.join(dst, filename))

When I run this whole Script it works until it has to move the files I get this error:

FileNotFoundError: [Errno 2] No such file or directory: 'XXX\\X15SL0447.JPG\n'

I know the file exist however the '\n' should not be there and that's why I am asking how can I still get everything on a new line and not have \n after each name so when I move the file the strings match.

Thank You For Your Help!

As they said above you should use .strip() :

shutil.copy(os.path.join(src, filename.strip()), os.path.join(dst, filename.strip()))

This way it gives you the file name or string you need and then it removes anything else.

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