[英]loop random line file text in python
我正在嘗試完成我的代碼。
文件文本,例如codetest.txt:
aaaa
eeeee
rrrrrrr
tttt
yyyyyy
uuuuu
iiiiiii
ooooo
ppppppppp
llllllll
我想要一個代碼,該代碼在文本文件中使用隨機行,然后將其打印到屏幕上,刪除文本文件中的打印行。 我已經完成了代碼。 有效:
import random
import sys
f = open("codetest.txt", "r")
lines = f.read().splitlines()
random_lines = random.sample(lines, 1)
code = "\n".join(random_lines) # var code
w = open("codetest.txt", "w")
w.writelines(line + "\n" for line in lines if line not in random_lines)
print("code :", code)
現在我想要一個循環,該循環將重復執行直到在空文本文件中為止。 我的代碼循環不起作用:
import random
import sys
i=0
while i<5:
i+=1
f = open("codetest.txt", "r")
lines = f.read().splitlines()
random_lines = random.sample(lines, 1)
code = "\n".join(random_lines) # var code
w = open("codetest.txt", "w")
w.writelines(line + "\n" for line in lines if line not in random_lines)
print("code",i," : ", code)
python中的一個小問題:如果不關閉文件, 它將永遠不會向其中寫入任何數據 。 (您的第一個程序起作用只是因為程序結束時python自動關閉了文件。)
嘗試添加w.close()
作為循環的最后一行。
在使用完文件后,最好關閉文件。 希望這可以幫助 :)
它缺少.close()
例:
w = open("codetest.txt", "w")
w.writelines( ...stuffs... )
w.close()
沒有.close()
,寫入的行將被緩沖在內存中。 對於第一種情況,退出程序時文件將自動關閉。 但是在后一種情況下, f
和w
不能正確關閉。
更好的樣式可以是這樣的:
with open("codetest.txt", "w") as w:
w.writelines( ...stuffs... )
with
語句將處理文件對象的生命周期。 https://docs.python.org/3.5/reference/compound_stmts.html#the-with-statement
我想要文件io練習,建議with open():
idiom
並看到list.pop(index)
通過一次執行2個所需的操作來符合代碼規范
print("code :", lines.pop(random.randrange(len(lines))))
幾乎完成所有非文件io工作
import random
import sys
txt = """aaaa
eeeee
rrrrrrr
tttt
yyyyyy
uuuuu
iiiiiii
ooooo
ppppppppp
llllllll
"""
with open('codetest.txt', 'w+') as f:
f.writelines(txt)
while True:
with open('codetest.txt', 'r') as f:
lines = f.read().splitlines()
if lines: # check if file is (not)empty
print("code :", lines.pop(random.randrange(len(lines))))
with open('codetest.txt', 'w') as f:
f.writelines(s+'\n' for s in lines)
else:
break # file is empty, break out of while loop
code : aaaa
code : tttt
code : ooooo
code : ppppppppp
code : iiiiiii
code : yyyyyy
code : llllllll
code : rrrrrrr
code : uuuuu
code : eeeee
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.