gpt4 book ai didi

Python - 从文件填充数组,避免最后断行

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

我正在寻找如何定义一个空数组并使用文本文件填充它,但在某一点上陷入困​​境,无法找到解决方案。

我的脚本是:

array=[]
file=open("path\\file.txt","r")
array.append(file.readline())
array.append(file.readline()) #wanted to put only first 2 line just for learning.
incident_count=len(array)
print(incident_count)
print(array)

第一个问题是,当我尝试将元素放入数组中时,还会附加换行符(“\n”)。还有一个用于将元素放入数组的右追加函数。

第二次,当我尝试打印数组的计数时,它正在打印字符的数量。

最佳答案

您可以使用file.readline()[:-1]这将返回除最后一个字符\n

之外的所有行
array.append(file.readline()[:-1])
array.append(file.readline()[:-1])

您可以添加 [:-1] 以避免最后一个字符 \n 考虑以下示例:

hello\n
world\n

因此,当您逐行读取文件时,每行都包含 \n ,因此为了避免 \n 您可以从索引 0 到索引读取该行-1

hello\n
^ ^_______index 4 or -1
|___________index 0

要了解更多信息,请看一下:

<小时/>
2
['hello', 'world']

或者像Omar Einea在他的评论中提到你可以使用:

array.append(file.readline().rstrip())
array.append(file.readline().rstrip())

如果最后一行没有 \n

关于Python - 从文件填充数组,避免最后断行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48960118/

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