Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中是否将“N”行从一个文件复制到另一个文件?_Python_Python 2.7_Scripting - Fatal编程技术网

在python中是否将“N”行从一个文件复制到另一个文件?

在python中是否将“N”行从一个文件复制到另一个文件?,python,python-2.7,scripting,Python,Python 2.7,Scripting,本质上,我试图做的是从一个文件中读取'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

本质上,我试图做的是从一个文件中读取'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
我也有文件打印来显示下一行变量中的内容

*['\n', "randomtext' more junk here\n"]
我希望它看起来像

 randomtext' more junk here
这是islice函数的限制吗?还是我遗漏了语法的一部分

谢谢你的时间

在调用str或print的位置,您希望。改为连接下一行:


如果不想调用join两次,可以将展平的字符串存储在变量中。

您的意思是这样的吗

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

你是说你不想把它列在名单上?您只需要.joinnext\n\u行吗?@nmichaels我正在尝试打印文字?\n基本上,字符从读取文件中提取新行,然后我将这些新行写入单独的文件中。基本上,任务是从一个文件中一次复制两行,然后将它们粘贴到一个新文件中。
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