[英]How would i put strings into an array from another text file (reading line by line) but only reading every other line
(在 txt 文件中)
line
line
notice that there's a blank line between line
我希望數組看起來像:x = [“line”,“line”,“注意行之間有一個空行”]
嘗試
txtFile = open("yourfile.txt").readlines()
x = [txtFile[i].strip() for i in range(len(txtFile)) if i % 2 == 0 ]
編輯:如果您只想刪除空白行,請嘗試將 x 變量行替換為
x = [txtFile[i] for i in range(len(txtFile)) if txtFile[i] != "\n"]
你可以這樣做 -
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"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.