gpt4 book ai didi

python - python中的writeline问题

转载 作者:太空宇宙 更新时间:2023-11-03 12:25:55 24 4
gpt4 key购买 nike

我有一个非常基本的问题。我正在学习 python 和脚本的第一步,所以即使这让我想知道:

我想在新文件中读取和写入行:

ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")

#read first line with headers
line1 = ifile.readline()
print line1

#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)

如果我将其打印到屏幕上,我会很好地完成所有行:

0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222

如果我将它写到 ofile,我最终会丢失大约 15 行:

0,6100,948,8332
0,26100,568,8636
0,11130,555

如果有人能指出我不明白的地方,我将不胜感激?

注册,

贾尼

最佳答案

您应该根据 python docs 调用 ofile.close() .

我不确定在没有明确关闭的情况下写入是否已完全刷新到文件中。

此外,正如 SilentGhost 提到的,检查输入文件中的空行。

正如下面 stefanw 所提到的,“if..break”语句在 for in 中不是必需的。

关于python - python中的writeline问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1126477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com