【问题标题】:My python code skips the first line of txt file?我的 python 代码跳过了 txt 文件的第一行?
【发布时间】:2020-05-20 22:45:14
【问题描述】:

所以我正在研究这段代码,它从 .txt 文件中复制行以在算法中使用它们,然后将结果保存到另一个文件中。该程序总是跳过第一行,而不是像在第一个 .txt 文件中那样输出 6 行,而是输出 5。我已经使用了很长时间,但似乎找不到导致它的原因。这是代码。

encryptString = []
counter = 0
dTagID = []
longVer = []
shortVer = []
#reading
fRead = open("certTags.txt", "r")
for line in fRead.readlines():
    dTagID.append(line)
lengthList = len(dTagID)
while counter < lengthList:
    tempSave = encryptSave + dTagID[counter]
    tempSave = int(tempSave)
    # Encryption
    msg = tempSave
    msge = msg**e
    msgn = msge % N
    msgn = str(msgn)
    longVer.append(msgn)
    # Checksum
    checksum = sum(map(int, msgn))
    checksum = str(checksum)
    shortVer.append(encryptSave+checksum)
    # Saving to file
    fWriteS = open("shortVer.txt", "a+")
    fWriteS.write(shortVer[counter] + '\n')
    fWriteL = open("longVer.txt", "a+")
    fWriteL.write(longVer[counter] + '\n')
    counter = counter + 1

【问题讨论】:

  • 首先,您的整个第一个循环可以替换为dTagID=list(fRead)。其次,在遍历列表时不要使用while。使用for。
  • @DYZ 照你说的做了,它仍然输出 5 个值,而不是输入的 6 个。我在它们被读取后输入了一个打印命令,它表明它们被正确复制了。

标签: python python-3.x list file read-write


【解决方案1】:

您的代码没有遵循许多最佳实践,这使得理解和调试变得困难。以下是我对如何使它更 Pythonic 的看法:

longVer = []
shortVer = []
#reading
with open("certTags.txt", "r") as fRead:
    for line in fRead:
        msg = int(encryptSave + line)
        # Encryption
        msg = str(msg**e % N)
        longVer.append(msg)
        # Checksum
        checksum = str(sum(map(int, msg)))
        shortVer.append(encryptSave + checksum)

# Saving to file
with open("shortVer.txt", "w") as fWriteS:
    fWriteS.write("\n".join(shortVer))
with open("longVer.txt", "w") as fWriteL:
    fWriteL.write("\n".join(longVer))

我不确定encryptSave 是什么,因为您从未定义过该变量。我假设它是一个字符串。

【讨论】:

  • 是的,做到了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
相关资源
最近更新 更多