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

时间:2018-12-19 20:31:24

标签: python

我正在运行此代码,并不断从\ n读取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))

3 个答案:

答案 0 :(得分:1)

打开文件时尝试使用换行符=“''

赞:

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

答案 1 :(得分:0)

我的猜测是,您的CSV在每个URL的末尾都有换行符,或者当您从APIKEY中捕获换行符时。我能想到的最简单的解决方法是:

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))

答案 2 :(得分:0)

您可以从Python尝试rstrip。这将返回删除了结尾字符的字符串副本。您可以使用url

url = url.rstrip('\n \t')进行转换

这是更改后完整代码的外观。

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))