基本上我尝试做的是从文件中读取'n'行,然后将它们写入单独的文件。该程序本质上应该采用一个包含100行的文件,并将该文件分成50个单独的文件。
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
我也有文件打印,以显示变量next_n_lines中的内容。
*['\n', "randomtext' more junk here\n"]
我希望它看起来像
randomtext' more junk here
这是islice功能的限制吗?或者我错过了部分语法?
谢谢你的时间!
答案 0 :(得分:0)
如果您致电str()
或print
,则需要''.join(next_n_lines)
代替:
print ''.join(next_n_lines)
和
fileout.write(''.join(next_n_lines))
如果您不想两次调用连接,可以将展平的字符串存储在变量中。
答案 1 :(得分:0)
你的意思是这样吗?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
或者这个粗略但有效的代码:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2