Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我有这样的功能:
f=open('file.txt','w') n=0 while(n<20): f.write(n) n=n+1 f.close()
但循环将所有数字写入文件,我只想要循环中的当前数字
例子:
1234567891011121314151617181920
with open('file.txt', 'w') as f: for n in range(20): f.write(str(n) + '\n')
或者:
with open('file.txt', 'w') as f: for n in range(20): print(n, file=f)