Python file write
2019-07-08 本文已影响0人
JaedenKil
from math import sqrt
def is_prime(n):
assert n > 0
for i in range(2, int (sqrt(n)) + 1):
if n % i == 0:
return False
return True if n != 1 else False
def main():
file_names = ['a.txt', 'b.txt', 'c.txt']
file_list = []
try:
for filename in file_names:
file_list.append(open(filename, 'w', encoding='utf-8'))
for n in range(1, 10000):
if is_prime(n):
if n < 100:
file_list[0].write(str(n) + "\r\n")
elif n < 1000:
file_list[1].write(str(n) + "\r\n")
else:
file_list[2].write(str(n) + "\r\n")
except IOError:
print("Error!")
finally:
for f in file_list:
f.close()
print("Complete!")
if __name__ == "__main__":
main()