简体   繁体   中英

Python write in the same line of file

Supose i have a function like this:

f=open('file.txt','w')
n=0
while(n<20):
    f.write(n)
    n=n+1
f.close()

but the loop writes all numbers to the file, and i just want the current number in the loop

example:

1234567891011121314151617181920
with open('file.txt', 'w') as f:
    for n in range(20):
        f.write(str(n) + '\n')

alternatively:

with open('file.txt', 'w') as f:
    for n in range(20):
        print(n, file=f)

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