Reputation: 2687
I have a text file IDlistfix
, which contains a list of youtube video IDs. I'm trying to make a new text file, newlist.txt
, which is the IDs in the first video with apostrophes around them and a comma in between the IDs. This is what I've written to accomplish this:
n = open('IDlistfix','r+')
j = open('newlist.txt','w')
line = n.readline()
def listify(rd):
return '\'' + rd + '\','
for line in n:
j.write(listify(line))
This gives me an output of ','rUfg2SLliTQ
where I'd expect the output to be 'rUfg2SLliTQ',
. Where is my function going wrong?
Upvotes: 0
Views: 76
Reputation: 4998
You just have to strip it of newlines:
j.write(listify(line.strip())) # Notice the call of the .strip() method on the String
Upvotes: 1
Reputation: 1968
Is a problem with change of line.
Change:
for line in n:
j.write(listify(line.replace('\n','')))
Upvotes: 1
Reputation: 537
The problem must be in,
`return '\'' + rd + '\`','
because rd is ending with '/n'. Remove the '/n' from rd and it should be fine
Upvotes: 1
Reputation: 9369
Try to remove trailing whitespace and return a formatted string:
n = open('IDlistfix','r+')
j = open('newlist.txt','w')
line = n.readline()
def listify(rd):
# remove trailing whitespace
rd = rd.rstrip()
# return a formatted string
# this is generally preferable to '+'
return "'{0}',".format(rd)
for line in n:
j.write(listify(line))
Upvotes: 1