[Tutor] Help merge files using python

Alan Gauld alan.gauld at btinternet.com
Thu Nov 14 02:27:20 CET 2013


On 13/11/13 22:26, jarod_v6 at libero.it wrote:

> I want to obtain
>
> A 10 0 60
> B 20 45 70
> C 30 0 10
> Z 0 10 0

Amit has given you a design to solve the problem, however based
on your code you may not be able to translate that into code yet.

> I try to do like this:
>   f = os.listdir(".")
> for i in f:
>   T =open(i,"r")
> for r in t.readlines():
> print r

First, note that indentation counts in Python
So your code opens each file and stores a reference in T.
But each assignment loses the previous one so you wind up with just the 
final file reference stored in T.

Second, note that Python is case sensitive so 't' and 'T' are not
the same name. So your second loop tries to read lines from t but
t does not exist.

Your code should look more like this

for f in os.listdir('.'):
     for r in open(f).readlines():
        print r

BTW it's better to use meaningful names rather than single letter
names for variables.

But that still won't really produce what you want, it will just
print out every line in every file.

Read Amit's mail and review the documentation on dictionaries
and sets. Try again and if you get stuck ask for more help.

And please don't post an entire digest next time, some people pay by the 
byte. Delete any messages that are not directly relevant.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list