打印换行但没有空格

Printing with newlines but no empty spaces

我正在解析一个 json 列表并在 txt 文件中打印 X 值。问题是我需要排除特定值,这样做会在列表中留下空白,如下所示:

CfZzroU5Zg3EEnmSdnURwu49XAdsUzJLqftAMsB6enQA
CJgzYGNSr1sioRituTStFkndugx4GrKv88r9XkbgNVh3


HJ1cZjtp9zxYAMNuTGvRB5inpmXuWVdoZy6RTWAF2vzf

9BTKTYTAyu3tEVWXHkQ155Er2ZhwxzQecePVpdyHCV5o


BCPt8Wc1TEKKw1M1WcnBWofKfKLBnapUXPyuX7EmqifY

6sGj9in9BCciX5D17EZsW4btfoTBWDx8AVR63ooUunHM

我想删除那些换行符,但我能找到的使用 end='' 执行此操作的唯一方法基本上删除了包括换行符在内的所有内容,结果如下所示:

PGoymXwWGHaF4ApyZLjcGRFvvFWVHZdDTdgkndg2WgEyspE9ik8Ay2ehyKRtntEY2tvQojQfj1rqrH5Ph91RSHqcRdWaayHug3QpcyuoctLkxcx2Sq3N2dmWcywzeHwL9uX2MJyJcE6HY9ZqNedVzUGUwmhZc6B7aSiCjs3UjohjYVoNX6orGqgFGCanq1NETb6r4ostLE96VGPchFGCq2ZRRepz4vZSTEdrVDrztPxqGRXqT9fHpkjjwkg1WM6k7kieSxrgakCgnAkkXB2s9wzixVzThdLKSp6qK5DJoDemTEhAHDix5n1ZSKiXhBNZ7rEP8AGByNL3XnNB5wJC7655VLgyYykC5ybdjpDzEEVnVpkvcFKqqstXyiA3jMdJiXCmXrz8iG5M1fXKhLhnG6CprKs71SJRHTyxhupdKi2Asatjbwh1mP9yXiQ8Q35AtH7MyRmmGifZhMsBCyKiHZqeSou9tZeN3f9ocqXi1792nBgiHi192q66wqJkeEPw6XpX2NJpii9qgDBzv1q7zjfWXEC6MP8pD8SSjid15q4uhNTBN9zx5i4dMimw61F4smh4wEVnVpkvcFKqqstXyiA3jMdJiXCmXrz8iG5M1fXKhLhnGHYVs2auZ3CvTy9GxgYZVYncJWEy5HHBHNYzoB5722zWbDLddoiBzRS6217u7gWuuWeFesLJbYVC7xETF3KjkSXTTFNZxe9FWdYCJVUdBpSpd4Quk4kG4SbGYDgcchkfxR72xCWkJA66uNbVdmUKmrmbdhdds2yxVnovVtzr8tqHvDKLM8FEZaEFxXqUwdtsGovSaJamty2kAz16ERTawdt8Bz8ZXGkEqvw25KQ6rZRHxyUeCJoJSV8Z47DCGNzR1bFE1pGLpFNZxe9FWdYCJVUdBpSpd4Quk4kG4SbGYDgcchkfxR72x3PkbfxGy1W6eSLfjwPuf1rYbst4GKkN2jBiz1jjZJfGM94UHpi9NnLjrnhGqzmE5dA7dSvgMewUjxorwzf2wJ6DV9J1xhdvqdf6ij9AWa3anGeP8iW9Htb32z2k3KLuxL2LV94UHpi9NnLjrnhGqzmE5dA7dSvgMewUjxorwzf2wJ6DV6gZRvYWEaXAVchYDvixUFiECS3UmQ3Cx65nYdt9DBVvtDueEQ2A3SsPKdFT5BYPS9AgWB6b7horZJuo5DCpRRjQL94UHpi9NnLjrnhGqzmE5dA7dSvgMewUjxorwzf2wJ6DV94UHpi9NnLjrnhGqzmE5dA7dSvgMewUjxorwzf2wJ6DVAFa

这是我正在使用的代码:

import json

with open('file.json') as json_file:
    data = json.load(json_file)

exclude = ['FFFFFFFFFFFFFFFFFFFFFFFFFFFF', 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBB', 'AAAAAAAAAAAAAAAAAAAAAAAAA', 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ']

with open("output.txt", "a") as f:
    for i in range(len(data)):
        if data[i]['owner'] in exclude:
            data[i]['owner'] = ''
        print (data[i]['owner'], end='', file=f)

如有任何帮助,我们将不胜感激! 谢谢

看起来常规打印语句应该与 else 语句一起使用:

with open("output.txt", "a") as f:
    for i in range(len(data)):
        if data[i]['owner'] in exclude:
            data[i]['owner'] = ''
        else
            print (data[i]['owner'], file=f)
       

您将需要跳过一些迭代以跳过不需要的值。您仍然可以使用 '\n' 作为分隔符!

with open("output.txt", "a") as f:
    for i in range(len(data)):
        if data[i]['owner'] in exclude:
            continue
        print (data[i]['owner'], end='\n', file=f)

我只是建议不要打印任何内容,以防字符串是应该排除的字符串。

with open("output.txt", "a") as f:
    for entry in data:
        if entry['owner'] in exclude:
            continue
        print (entry['owner'], file=f)