[英]I'm trying to export a Python list to a .txt file, but the text file ends up having too few lines
[英]I'm trying to write random numbers to a file and then make a list from lines in Python but list takes '\n' too
我正在使用一個函數來創建隨機數,並使用以下代碼塊在 for 循環中使用\\n
在名為random.txt
的文件中random.txt
寫入它們:
dosya.write(str(randomNumber))
dosya.write('\n')
我需要從行中創建一個列表,然后使用排序函數對該列表進行排序。 我可以在該文件中逐行查看我的隨機數,但是當我使用readline()
函數時,例如:
List = open("random.txt").readlines()
print List
輸出是:
['22\n', '16\n', '1\n', '4\n', '4\n']
為什么我在數字后面看到\\n
? 我嘗試只打印第一個或第二個元素,但沒有顯示任何額外的東西。 整個列表有什么問題? 當我使用 sort 函數時,它也需要\\n
。
循環遍歷每一行並將該行轉換為 int 並附加到數組。
f=open('random.txt','r')
array = []
for line in f: # read lines
array.append(int(line))
f.closed
.readlines()
方法讀取每一行,包括以\\n
結尾的行作為列表元素。 無論如何,您可能希望您的隨機數為整數。 將它們轉換為int
也會使您的排序工作:
with open("random.txt") as fobj:
data = [int(line) for line in fobj]
with
打開文件並承諾在您離開縮進時立即關閉它。 打開的文件對象fobj
是可迭代的。 因此,您可以直接在fobj
編寫一個列表fobj
將每一行轉換為一個整數。 它會自動刪除所有換行符n
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.