我想要实现的是将单个文件中的条目列表分成多个文件,如下所示。
列表:
www.a.com/thing1.html
www.b.com/thing2.html
www.c.com/thing3.html
将单行条目保存到文件中,其中新文件看起来像这样
例如第一个条目 -
文件名为thing1.txt
。
文件中的内容为:
[some static text common to all files]www.a.com/thing1.html[more static content]
让它在列表文件中的所有条目上循环运行,直到耗尽列表。不确定for循环是否可以在这里工作,或者是一个while循环。
我刚开始学习python,其中一些功能(创建文件,指定文件名)对我来说仍然很陌生。
答案 0 :(得分:1)
我告诉你一个文件,但对于你的情况,你可以iterate over your list来实现同样的目标。
我将使用I/O module for file handling和re module从您的链接中提取thing1
。
>>> st = "www.a.com/thing1.html"
>>> filename = re.findall(r"/(\w+).",st)
>>> filename
['thing1']
>>> filename = "".join(filename) + '.txt'
>>> filename
'thing1.txt'
>>> f = open(filename,'w')
>>> f.writelines(st)
您也可以将list
传递给writelines
。
mylist = ["some static text common to all files",st,"more static content"]
f.writelines(mylist)