[英]How would i put strings into an array from another text file (reading line by line) but only reading every other line
(in txt file) (在 txt 文件中)
line
line
notice that there's a blank line between line
I would want the array to look like: x = [“line”, “line”, “notice that there's a blank line between line”]我希望数组看起来像:x = [“line”,“line”,“注意行之间有一个空行”]
Try尝试
txtFile = open("yourfile.txt").readlines()
x = [txtFile[i].strip() for i in range(len(txtFile)) if i % 2 == 0 ]
Edit: If you just want to remove blank lines try replacing the x variable line with编辑:如果您只想删除空白行,请尝试将 x 变量行替换为
x = [txtFile[i] for i in range(len(txtFile)) if txtFile[i] != "\n"]
You can do it in this way -你可以这样做 -
with open("file_name.txt") as file:
result = [line.rstrip() for line in file if line.rstrip()]
print (result)
O/P: ['line', 'line', "notice that there's a blank line between line"]
O/P:
['line', 'line', "notice that there's a blank line between line"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.