如何打印我们在另一个目录中写入的文本文件的路径,并在Python中的每个文件中打印字符串
如何打印我们刚刚打印到文本文件的路径。例如: 我在D:/Workspace/Python/textfile.txt上有textfile.txt路径。你有这样的绳子吗如何打印我们在另一个目录中写入的文本文件的路径,并在Python中的每个文件中打印字符串,python,Python,如何打印我们刚刚打印到文本文件的路径。例如: 我在D:/Workspace/Python/textfile.txt上有textfile.txt路径。你有这样的绳子吗 string1 i have pen i have book string2 i have ruler i have bag author : stevanus 然后将textfile.txt拆分为两个文件,打印每个textfile上的路径。在每个文件中打印其上方的路径和下方的作者。在D:/Workspace/savedfile上
string1
i have pen
i have book
string2
i have ruler
i have bag
author : stevanus
然后将textfile.txt拆分为两个文件,打印每个textfile上的路径。在每个文件中打印其上方的路径和下方的作者。在D:/Workspace/savedfile上的另一个路径中。范例
在textfile1.txt中
path : D:/Workspace/savedfile/textfile1.txt <-- print the path but textfile1.txt
string1
i have pen
i have book
author : stevanus <-- print the author
简而言之,如何打印存储的新文件的路径,以及如何将字符串从原始文件打印到所有新文件。很抱歉我的英语不好我认为itertools.chain是分割文件的更好方法 在for循环之后,变量“line”变成“author:stevanus”,然后可以将它添加到除最后一个文件之外的每个文件中
from itertools import chain
filename = 'D:/Workspace/Python/textfile.txt'
with open(filename, 'rb') as inf:
header = next(inf)
for index, line in enumerate(inf,start=1):
with open('D:/Workspace/Python/textfile{}.txt'.format(index) ,'w') as outf:
outf.write('Path : %s\n' %outf.name)
outf.write(header)
for line in chain([line], inf):
if 'string' in line:
header = line
break
outf.write(line)
for idx in range(1, index):
filename = 'textfile{}.txt'.format(idx)
with open(filename, 'a') as outf:
outf.write(line)
你可以简单地:
- 每次在一行中找到
字符串时打开一个新文件
- 将所有打开的文件保存在列表中
- 当您在一行中找到
时,将该行添加到所有打开的文件中并关闭它们author
linenum = 1
files = []
with open('D:/Workspace/Python/textfile.txt', 'rt') as inf:
for line in (inf):
if 'string'in line:
filename = 'D:/Workspace/Python/textfile{}.txt'.format(linenum)
fd = open(filename,'w')
linenum+=1
files.append(fd)
elif 'author' in line:
for fd in files:
fd.write(line)
fd.close()
break
fd.write(line)
如果文件格式不正确,您应该添加一些错误处理,但它适用于正确的输入文件。首先必须从源文件中获取最后一行。否则你就写不出这句话了。我想问问。如何从底部获得另一条2行字符串。例如,作者字符串之前有日期字符串。我需要两个字符串打印。。谢谢
from itertools import chain
filename = 'D:/Workspace/Python/textfile.txt'
with open(filename, 'rb') as inf:
header = next(inf)
for index, line in enumerate(inf,start=1):
with open('D:/Workspace/Python/textfile{}.txt'.format(index) ,'w') as outf:
outf.write('Path : %s\n' %outf.name)
outf.write(header)
for line in chain([line], inf):
if 'string' in line:
header = line
break
outf.write(line)
for idx in range(1, index):
filename = 'textfile{}.txt'.format(idx)
with open(filename, 'a') as outf:
outf.write(line)
linenum = 1
files = []
with open('D:/Workspace/Python/textfile.txt', 'rt') as inf:
for line in (inf):
if 'string'in line:
filename = 'D:/Workspace/Python/textfile{}.txt'.format(linenum)
fd = open(filename,'w')
linenum+=1
files.append(fd)
elif 'author' in line:
for fd in files:
fd.write(line)
fd.close()
break
fd.write(line)