繁体   English   中英

\ 在一个txt的每一行的末尾

[英]\ in the end of each line of a txt

我想将图像的路径名写入 python 中的 a.txt。 A 为每个路径创建一个新行,但它会在每个图像的末尾创建一个不需要的 \。 我试图剥离它但没有任何反应。 我怎样才能剥离它?

for num, name in enumerate(dirNames):
    os.mkdir(name)
    os.chdir(name)
    with open(f'{os.path.basename(name)}.txt', 'w+', encoding = 'utf-8') as f:
        for tile in png_cropedShips[num]:
                
                path = os.path.join('tiles', os.path.basename(name), os.path.basename(tile),'\n')
                print(path)
                f.write(path)
        for line in f:
            line.rstrip('\\')

output:

tiles\T34TBL20211001T094041\T34TBL_20211001T094041_c38_r9_ndwi.png\
tiles\T34TBL20211001T094041\T34TBL_20211001T094041_c39_r0_ndwi.png\
tiles\T34TBL20211001T094041\T34TBL_20211001T094041_c39_r12_ndwi.png\
tiles\T34TBL20211001T094041\T34TBL_20211001T094041_c39_r13_ndwi.png\
path = "a\\string\\"
path = path.removesuffix("\\")

print(path)

将打印:

a\string

应该这样做,当使用反斜杠时,您应该将它们两次放在一个字符串中,因为它有点忽略第一个。

正确的 output 是通过将换行符与图像路径分开编写来实现的!

for num, name in enumerate(dirNames):
    os.mkdir(name)
    os.chdir(name)
    with open(f'{os.path.basename(name)}.txt', 'w+', encoding = 'utf-8') as f:
        for tile in png_cropedShips[num]:
                path = os.path.join('tiles', os.path.basename(name), os.path.basename(tile))
                
                f.write(path)
                f.write('\n')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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