简体   繁体   中英

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?

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. 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. This returns a copy of the string with trailing characters removed. You can transfrom url using 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))

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