[Tutor] a quick Q: how to use for loop to read a series of files with .doc end

Andreas Perstinger andreas.perstinger at gmx.net
Thu Oct 6 18:13:06 CEST 2011


On 2011-10-06 16:11, lina wrote:
> I still don't know how to (standard) convert the list values to a string.
>
> def writeonefiledata(outname,results):
>      outfile = open(outname,"w")
>      for key, value in results.items():
>          print(value)
>          outfile.write(str(results[key]))
> Is it a wrong way?

There isn't really a wrong way because it's completely up to you how the 
list (or its elements) should be represented. As you will have noticed, 
"str(list)" just gives you the standard representation in Python (all 
list elements separated by a comma inside square brackets):
 >>> str([1, 2, 3, 4])
'[1, 2, 3, 4]'

But I think you want something else because earlier you wrote:

On 2011-10-04 18:38, lina wrote:
 > For file:
 >
 > aaEbb
 > aEEbb
 > EaEbb
 > EaEbE
 >
 > the expected output is
 >
 > 2 1 0 1

(Although I suppose, as Alan already noticed, that you've forgotten to 
mention the third column and the output should be: 2 1 4 0 1)

So you have to build your own string. You could use the join method. It 
takes a list and concatenates the list elements to a string separated by 
the given string object:
 >>> "".join(["1", "2", "3"])
'123'
 >>> "-".join(["1", "2", "3"])
'1-2-3'

The problem now is that "join" will only join the list elements if they 
are strings but in your case the list elements are integers. You have to 
convert them before you can concatenate them. In Python that's usually 
the job of a list comprehension but I'm not sure if you already know 
what that is. So for a start you can also use a for-loop:
 >>> l = []
 >>> for number in [1, 2, 3]:
...     l.append(str(number))
...
 >>> l
["1", "2", "3"]

You must also be aware that when you write your new strings into a file 
that "write" doesn't append a newline ("\n") to each string (in contrast 
to "print"). So you have to do it manually if you don't want to write 
just a long list of numbers.

Bye, Andreas



More information about the Tutor mailing list