Python write problem

I have a major problem. I study my first steps with python and scripts in general, and therefore even this makes me wonder:

I want to read and write lines to a new file:

ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")

#read first line with headers
line1 = ifile.readline()
print line1

#read following lines which contain data & write it to ofile
for line in ifile:
    if not line:
        break
    ofile.write(line)

If I print this on the screen, I will get all my lines:

0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222

If I write it in toile, I will end up skipping about 15 lines:

0,6100,948,8332
0,26100,568,8636
0,11130,555

I would appreciate if someone could tell me what I do not understand?

Reg,

Jaani

+3
source share
5 answers

You should call toile.close () according to python docs .

I am not sure if the entries are completely deleted to the file without explicit closure.

Also, as mentioned in SilentGhost, check for empty lines in the source file.

, , stefanw, "if.. break" in.

+5
#read following lines which contain data & write it to ofile
for line in ifile:
    if not line:
        continue          #break stops the loop, you should use continue
    ofile.write(line)
+4

"if not line:" - .

for line in ifile:
    ofile.write(line)
+3

python2.4? python2.6

from contextlib import nested
ipath = "C:\Python24\OtsakkeillaSPSS.csv"
opath = "C:\Python24\OtsakkeillaSPSSout.csv"
with nested(open(ipath,'r'), open(opath,'w') as ifile, ofile:

    #read first line with headers
    line1 = ifile.readline()
    print line1

    #read following lines which contain data & write it to ofile
    for line in ifile:
        ofile.write(line)
+1

, , ? ...

,

. python , :

:

ifile = open ( "C:\Python24\OtsakkeillaSPSS.csv", "r" ) ofile = open ( "C:\Python24\OtsakkeillaSPSSout.csv", "w" )

line1 = ifile.readline() 1 , toile

ifile:    :          ofile.write()

If I print this on the screen, I will get all my lines:

0,26100,568,8636 0,11130,555,3570 0,57100,77,2405 0,60120,116,1193 0,33540,166,5007 0,95420,318,2310 0,20320,560,7607 0 , 4300.692.3969 0.65610.341.2073 0.1720.0.0 0.78850,228.1515 0.78870,118,1222

If I write it in toile, I will end up skipping about 15 lines:

0.6100.948.8332 0.26100.568.8636 0.11130.555

I would appreciate if someone could tell me what I do not understand?

Reg

Jaani

0
source

Source: https://habr.com/ru/post/1712576/


All Articles