import os # 第一步:创建目录 dir_name = "fibonacci" if not os.path.exists(dir_name): os.mkdir(dir_name) # 第二步:将斐波那契数列的前1000个数据写入文件fib_data.txt print("正在将斐波那契数列的前1000个数据写入文件...") fib_list = [0, 1] for i in range(2, 1000): fib_list.append(fib_list[i-1] + fib_list[i-2]) with open(os.path.join(dir_name, "fib_data.txt"), "w") as f: for i, num in enumerate(fib_list): f.write("第 {} 个数是:{}\n".format(i+1, num+1)) print("完成!") print("fib_data 已保存") # 第三步:截取fib_data.txt文件的第899-920行,并写入新文件fib_part_data.txt print("正在截取数据...") with open(os.path.join(dir_name, "fib_data.txt"), "r") as f1: lines = f1.readlines() with open(os.path.join(dir_name, "fib_part_data"), "w") as f2: for line in lines[898:919]: f2.write(line) print("完成!") print("fib_part_data 已保存") # 第四步:显示fib_part_data.txt文件内容 with open(os.path.join(dir_name, "fib_part_data.txt"), "r") as f: print(f.read())截取的切片怎么隔一行输出一行
时间: 2024-02-24 10:53:06 浏览: 79
ACM.rar_ACM_acm icpc _icpc_site:www.pudn.com_visual c
要让截取的内容每行隔一行输出,可以在写入新文件 fib_part_data.txt 时,每写入一行数据后再写入一个空行即可。修改代码如下:
```
print("正在截取数据...")
with open(os.path.join(dir_name, "fib_data.txt"), "r") as f1:
lines = f1.readlines()
with open(os.path.join(dir_name, "fib_part_data.txt"), "w") as f2:
for i, line in enumerate(lines[898:919]):
f2.write(line)
if i % 2 == 0: # 每隔一行写入一个空行
f2.write("\n")
print("完成!")
print("fib_part_data 已保存")
# 第四步:显示fib_part_data.txt文件内容
with open(os.path.join(dir_name, "fib_part_data.txt"), "r") as f:
print(f.read())
```
这样就可以实现每行隔一行输出了。
阅读全文