2012-08-28 81 views
0

我想创建基于列表的批量文本文件。文本文件包含多行/标题,目标是创建文本文件。以下是我的titles.txt与非工作代码和预期输出的关系。Python空白txt文件创建

titles = open("C:\\Dropbox\\Python\\titles.txt",'r') 
for lines in titles.readlines(): 
     d_path = 'C:\\titles'  
    output = open((d_path.lines.strip())+'.txt','a') 
    output.close() 
titles.close() 

titles.txt
Title-A
Title-B
Title-C

new blank files to be created under directory c:\\titles\\
Title-A.txt
Title-B.txt
Title-C.txt

+4

只是一个建议:你可能想用[os.path.join()](http://docs.python.org/library/os.path.html#os.path.join)代替字符串连接和strip()等 – Levon

+0

而不是追加,也许你应该打开“W”选项? –

+1

(1)你的问题是什么? (2)你确定'd_path.lines.strip()'的语法吗?你想连接一些字符串吗? –

回答

2

这是一个有点很难告诉你正在试图在这里是什么,但希望这会有所帮助:

import os.path 
with open('titles.txt') as f: 
    for line in f: 
     newfile = os.path.join('C:\\titles',line.strip()) + '.txt' 
     ff = open(newfile, 'a') 
     ff.close() 

如果要替换现有的文件与空白文件,您可以打开您的文件模式'w'而不是'a'

+0

你不想'w'作为模式吗? (认为​​PR由OP发布仍然有点不清楚) – Levon

+0

@Levon - 这取决于用户是否想用空白文件替换*现有文件*。使用''w''对我来说似乎很危险,所以我避免了这一点,但我更新了评论。 – mgilson

+0

是的..好点..希望OP会澄清(你的编辑是好的) – Levon

1

以下应该工作。

import os 
titles='C:/Dropbox/Python/titles.txt' 
d_path='c:/titles' 
with open(titles,'r') as f: 
    for l in f: 
     with open(os.path.join(d_path,l.strip()),'w') as _: 
      pass 
+2

'l'作为变量名不是最可读的选择。 –