简体   繁体   中英

file program reading and writing python

endofprogram=False
try:
    filename=input('Enter file name: ')
    filename2=input('Enter file to write: ')
    infile=open(filename,'r')
    outfile=open(filename,'w')


    #IOError if file is not found
except IOError:
    print('End reading file--end of program')
    endofprogram=True

if(endofprogram==False):
    total=0
    alist=[]

    for line in infile:
        line=line.strip('\n')

        if(len(line)!=0)and line[0]!='#':
            name,grade=line.split('\t')
            total=total+float(grade)
            record=(name,float(grade))
            alist.append(record)

Here I am trying to write into a new file.

            outfile.write(name+'\n'+str(grade))

    average=total/len(alist)
    for item in alist:
        if item[1]<average:
            print(item)

    infile.close()

Hey guys. I was trying to understand file programs in python and just had a few questions.

2.Is my write into a new file statement correct because it gives me 'ZeroDivisionError after second line?

3. name,grade=line.split('\\t') work same as name,grade=line.split() ?

Appreciate everyones effort . Thanks

I made a few changes to your code and got it to work:

1) I open the first file, read it into a list and then close it

2) Also, you are opening both the files with the same name filename . It is a mistake. I think you meant to do filename2 for the second open

To answer your question 3): Yes string.split() is the same thing as string.split('\\t')

HERE is the working program:

endofprogram=False
try:
    filename=str(input('Enter file name: '))
    filename2=str(input('Enter file to write: '))
    infile_temp=open(filename,'r')
    infile=infilea.readlines()
    infile_temp.close()
    outfile=open(filename2,'w')

    #IOError if file is not found
except IOError:
    print('End reading file--end of program')
    endofprogram=True

if(endofprogram==False):
    total=0
    alist=[]

    for line in infile:
        line=line.strip('\n')

        if(len(line)!=0)and line[0]!='#':
            name,grade=line.split()
            total=total+float(grade)
            record=(name,float(grade))
            alist.append(record)

            outfile.write(name+" "+str(grade)+'\n')

    average=total/len(alist)
    for item in alist:
        if item[1]<average:
            print item

HOPE THAT HELPS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM