how to write list in a file
David Palao
dpalao.python at gmail.com
Wed Apr 23 04:40:44 EDT 2014
2014-04-23 9:53 GMT+02:00 Dhananjay <dhananjay.c.joshi at gmail.com>:
> Hello everyone,
>
> I am trying hard to write a list to a file as follows:
>
>
> def average_ELECT(pwd):
> os.chdir(pwd)
> files = filter(os.path.isfile, os.listdir('./'))
> folders = filter(os.path.isdir, os.listdir('./'))
> eelec = 0.0; evdw = 0.0; EELEC = []; elecutoff = [];
> g = Gnuplot.Gnuplot()
> for f1 in files:
> # if f1[21:23]=='12':
> if f1[27:29]==sys.argv[1]: # vdw cutoff remains constant; see 2nd
> column of output
> fl1 = open(f1,'r').readlines()
> # print len(fl1)
>
> for i in range(1, len(fl1)):
> fl1[i]=fl1[i].split()
> eelec = eelec + float(fl1[i][1])
> evdw = evdw + float(fl1[i][2])
> #print fl1[i][1], fl1[i][2]
> avg_eelec = eelec/40
> avg_evdw = evdw/40
> # print eelec, evdw
> # print f1[21:23], f1[27:29], avg_eelec, avg_evdw
> print f1[21:23], f1[27:29], avg_eelec
> # EELEC.append(avg_eelec); elecutoff.append(float(f1[21:23]))
> eelec=0.0; evde=0.0;
> a = f1[21:23]+' '+f1[27:29]+' '+str(avg_eelec)
> EELEC.append(a)
> print sorted(EELEC)
> with open('EElect_elec12-40_vdwxxx.dat','w') as wr:
> for i in EELEC:
> print i
> wr.write("%s\n" % i)
> wr.close()
>
>
> The script is printing "print sorted(EELEC)" as well as "print f1[21:23],
> f1[27:29], avg_eelec" very well.
> However, for some reason, I neither see any file (expected to see
> EElect_elec12-40_vdwxxx.dat as per the script) generated nor any error
> message.
>
> Could anyone suggest me correction here.
>
> Thanking you in advance.
>
> -- DJ
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
A couple of minor points:
* You don't need "wr.close()" after the "with open(...) as wr:" block.
* Are you sure that you are looking in the right directory?
* Why do you need the "g = Gnuplot.Gnuplot()" line? It looks to me
that you have skipped some things while doing copy and paste?
Best regards
More information about the Python-list
mailing list