Saturday, March 30, 2019

PYTHON read and write file

When we wants to read some file especially with text file, we will used the read and write methods.


 line = line.strip()  and print(line,end='') is the same.
If you don't used this two code, it will automatic add new line to each line while it read the text file.



===========================Source code===================


EXAMPLE1:

 METHOD1

with open('test.txt') as f,open('out.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
        print(line)

 METHOD2

with open('test.txt') as f,open('out.txt', 'w') as f_out:
    for line in f:
        print(line,end='')




Note:
There are two ways to implement this function on reading a file from text file.
You can use line.strip or use (ine,end’’)


OUTPUT:



EXAMPLE2:


with open('test.txt') as f,open('out.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
        #print(line)
        f_out.write('{}\n'.format(line))
    

 NOTE:

Output to a file need to use this:
f_out.write('{}\n'.format(line))

OUTPUT:

EXAMPLE3:
 

sum=0
count=0
for grade in open('grade.txt'):
    print(grade, end='')
    sum=sum+int(grade)
    count=count+1
average =sum/count
print("Aaverage:"+str(average))

 OUTPUT:
 






No comments:

Post a Comment