2
votes

I am trying to take a text file with dates and reformat them. Ex: '1/31/2017' becomes '2017-1-31T:00:00:00Z'

Code:

with open("test.rtf") as f:
    data = f.readlines()

for line in data:
    a,b,c = line.split("/")

    if len(a) < 2:
        a = "0" + a

    if len(b) <2:
        b = "0" + b

    print(c,"-",a,"-",b,"T:00:00:Z")

However, it is returning an error: Traceback (most recent call last): File "pubdateformat.py", line 8, in a,b,c = line.split("/") ValueError: need more than 1 value to unpack

Can anyone explain what this is saying?

Thanks for the help!

2
Indeed line.split("/") looks to be returning a list with only 2 items. For what it's worth though, I'd recommending looking into the datetime library to do this for you rather than manually converting strings. In particular, look into strftime and strptime. - thesilkworm
Your data seems to contain lines with no "/" so split will return just the line. - pask

2 Answers

0
votes

You are reading a .rtf file as if it's .txt file. RTF is a text file format used by Microsoft products, such as Word and Office.

If you try the same example with a text file it should work fine. Either get a library to read .rtf file or use text file and same code should work.

In [17]: with open("test.txt") as f:
    ...:     data = f.readlines()
    ...:
    ...: for line in data:
    ...:     a,b,c = line.split("/")
    ...:
    ...:     if len(a) < 2:
    ...:         a = "0" + a
    ...:
    ...:     if len(b) <2:
    ...:         b = "0" + b
    ...:
    ...:     print(c,"-",a,"-",b,"T:00:00:Z")
    ...:

OUTPUT  ('2017', '-', '01', '-', '31', 'T:00:00:Z')
0
votes

Your error points to this.

Your variable "data" has at least one value which does not have a date format which you are expecting. That is why it is facing issues to assign values to a,b and c. Please check your variable data. You can do that by adding a line inside your for loop preferably at the start of for loop

print(line)  ## This is by python3

If it does not solve your issue please post a sample file that you are reading.