2

I have a function to create and write some info to a .txt file. I have to write it like this:

11:13, Andrej Hlavac, Zdenka Sedlak

But instead, I get:

11:13, Andrej Hlavac, Zdenka Sedlak, 

The function that writes this output is:

def write_assignments_file(assignments, header, file_name):
        header[1]=str(dateTime.date(header[3],header[1],5))                  
        header='\n'.join(header)                                
        timetable=open(file_name,'w')                   
        timetable.write(str(header)+'\n')
        timetable.write('Timetable:'+'\n')
        for i in range(len(assignments)):
                for re in assignments[i]:
                        timetable.write(str(re)+', ')
                timetable.write('\n')
        timetable.close()
Nypt008
  • 103
  • 9

1 Answers1

3

You're current code adds a ', ' after every element so of course there will be one at the end. The str.join(sep, it) method only puts the sep string in between each element of it.

So replace

for re in assignments[i]:
    timetable.write(str(re)+', ')

with

 timetable.write(', '.join(map(str, assignments[i])))

For the record, never do

for i in range(len(assignments)):
     do_something(assignments[i])

instead do

for assignment in assignments:
     timetable.write(', '.join(map(str, assignment)))

If you need the indices of assignments, use enumerate.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • I'm curious why you should never do `for i in range(len(x))`, could you elaborate more on that? – Treyten Carey Dec 14 '17 at 17:39
  • Well you can, but it's not very [pythonic](https://stackoverflow.com/questions/25011078/what-does-pythonic-mean). It screams "I've come from another language and don't really know what I'm doing in python". While it's often necessary in say, C++, to do `for (int i = 0; i != a.size(); i++){f(a[i]);}`, in python it's far more clear what you're doing when you do `for elem in a: f(elem)` or `for index, elem in enumerate(a): f(index, elem)`. There's also the issue that python iterators are commonly generators, which have no `__len__` method, so `len(gen)` will fail. Try `len(zip(x,y))` – FHTMitchell Dec 14 '17 at 17:52