本质上,我试图做的是从文件中读取'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函数的极限吗?还是我缺少语法的一部分?
谢谢你的时间!
在您致电str()
或的地方print
,您想''.join(next_n_lines)
改为:
print ''.join(next_n_lines)
和
fileout.write(''.join(next_n_lines))
如果不想两次调用join,可以将扁平化的字符串存储在变量中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句