简体   繁体   English

如何避免在for循环的print语句中打印\\ n?

[英]How to avoid printing of \n in print statement inside for loop?

I am running this code and keep getting a \\n from reading the newline in the csv file, how can I prevent this? 我正在运行此代码,并在读取csv文件中的换行符时不断得到\\ n的信息,如何防止这种情况发生?

with open('test.csv', '') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_file:
        xurl = "/contacts/v1/contact/email/{row}/profile".format(**vars())
        url = HS_API_URL + xurl + APIKEY
        print url
        data = {
            "properties": [
                {
                    "property": "hs_lead_status",
                    "value": "UNQUALIFIED"
                }
            ]
        }
        r = requests.post(url, headers=header, data=json.dumps(data))

Try to use newline='' when you open file 打开文件时尝试使用换行符=''

Like: 喜欢:

with open(test.csv, 'r', newline='') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            for line in reader:
                print(line)

My guess is that your CSV has newlines at the end of each URL or maybe you caught a newline when from your APIKEY. 我的猜测是,您的CSV在每个URL的末尾都有换行符,或者当您从APIKEY中捕获换行符时。 easiest fix I can think of is this: 我能想到的最简单的解决方法是:

with open('test.csv', '') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_file:
        xurl = "/contacts/v1/contact/email/{row}/profile".format(**vars())
        url = HS_API_URL + xurl + APIKEY
        print(url.replace('\n',''))
        data = {
            "properties": [
                {
                    "property": "hs_lead_status",
                    "value": "UNQUALIFIED"
                }
            ]
        }
        r = requests.post(url, headers=header, data=json.dumps(data))

You can try rstrip from Python. 您可以从Python尝试rstrip This returns a copy of the string with trailing characters removed. 这将返回删除了结尾字符的字符串副本。 You can transfrom url using url = url.rstrip('\\n \\t') 您可以transfrom url使用url = url.rstrip('\\n \\t')

This is how your full code will look after the change. 这是更改后完整代码的外观。

with open('test.csv', '') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_file:
        xurl = "/contacts/v1/contact/email/{row}/profile".format(**vars())
        url = HS_API_URL + xurl + APIKEY
        url = url.rstrip('\n \t')    #New line which removes trailing `\n`.
        print url
        data = {
            "properties": [
                {
                    "property": "hs_lead_status",
                    "value": "UNQUALIFIED"
                }
            ]
        }
    r = requests.post(url, headers=header, data=json.dumps(data))

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

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