2017-08-11 30 views
0

我试图完成我的代码。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) 
+0

请详细告诉我。 我是新pythoner 谢谢 – Chellam

+0

不''而1 <2:'。这将是'当我<2:'时。 –

+0

而I <2: ERRO:C:\ python3.6 \ python.exe E:/Python/ex/test/test.py 代码1:YYYYYY 回溯(最近最后调用): 文件“E :/Python/ex/test/test.py“,第36行,在 random_lines = random.sample(lines,1) 文件”C:\ python3.6 \ lib \ random“。py“,第317行,样本 raise ValueError(”样本大于总体或负数“) ValueError:样本大于总体或为负 – Chellam

回答

0

Python中的小怪癖,如果不关闭文件,它永远不会写入任何数据它。 (你的第一个程序只工作,因为python在程序结束时自动关闭文件。)

尝试添加w.close()作为循环的最后一行。

当您完成使用它们时关闭文件是一种很好的做法。希望这有助于:)

+0

Tuyệtvời,nóđãlàmviệc。cảmơn.Thatis my shortcoming。 – Chellam

0

它遗漏.close()

例子:

w = open("codetest.txt", "w") 
w.writelines(...stuffs...) 
w.close() 

没有.close(),书写线将缓存在内存中。对于第一种情况,退出程序时文件将自动关闭。但在后一种情况下,fw未正确关闭。

更好的风格,可以是这样的:

with open("codetest.txt", "w") as w: 
    w.writelines(...stuffs...) 

with语句将处理文件对象的生命周期。 https://docs.python.org/3.5/reference/compound_stmts.html#the-with-statement

+0

这是我的缺点。 – Chellam

0

我想IO实践文件,使用推荐with open():成语

,看到list.pop(index)通过一次

print("code :", lines.pop(random.randrange(len(lines))))做2个所需的操作符合代码规范做几乎所有的非文件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