Python Forum
openpyxl and newline characters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
openpyxl and newline characters
#1
Why won't openpyxl accept newline characters??

Yesterday I wanted to put some questions in an excel file. The questions are in a text file, each on a separate line.

Qs = open(questions)
Qs_data = Qs.readlines()
Got the questions, now I want to put them in the wb. In the Python shell I saw the output from Python writing to the cells concerned.

When I saved and opened the workbook: No questions, but Python showed no error!

Took me a while to realize that the newline characters were causing the problem. I put Q = thisQ.strip(), then it worked.

#put the questions in the wb column 1
    # they are long
    # start in row 3, increment by 5 each time
    count = 3
    # num is for the question numbers here
    num = 1
    for q in Qs_data:
        thisQ = 'Q'+str(num) + ': ' + q
        # for some reason openpyxl won't accept \n
        # no error, but nothing gets written, so need to strip away the \n
        Q = thisQ.strip()
        print(thisQ)
        wb[this_survey].cell(row=count, column=1, value=Q)
        # this is for the percent values
        wb[this_survey].cell(row=count+75, column=1, value=Q)
        count+=5
        num+=1
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading integers from a file; the problem may be the newline characters JRWoodwardMSW 2 612 Jul-14-2020, 02:27 AM
Last Post: bowlofred
  Remove escape characters / Unicode characters from string DreamingInsanity 5 2,552 May-15-2020, 01:37 PM
Last Post: snippsat
  [Python3] Trailing newline in readlines. LWFlouisa 4 1,413 Mar-10-2020, 09:57 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020