2014-10-12 185 views
0

我正在创建一个脚本,用于将文本文件中提到的所有文件复制到某个目标。从文本文件中删除所有文件的脚本

这是我的脚本:

with open('names.txt') as f: 
    for line in f: 
     a = 'cp ' + line + ' /root/dest1' 
     print a 
     os.system(a) 

这是打印下面的命令:

(Incorrect) 

cp 91.txt 
/root/dest1 
cp 92.txt 
/root/dest1 
cp 93.txt 
/root/dest1 
... 

虽然它应打印这样的:

(correct) 

cp 91.txt /root/dest1 
cp 92.txt /root/dest1 
cp 93.txt /root/dest1 
... 

这是我的文件

(names.txt) 

91.txt 
92.txt 
93.txt 
94.txt 
95.txt 
96.txt 
97.txt 
98.txt 
99.txt 
9.txt 

任何人都可以帮我解决这个问题。顺便说一句,我打印命令只是为了知道什么是错的。

+1

尝试:'line.strip()' – kev 2014-10-12 07:14:52

+0

你想删除变量行上的换行符 – user2601995 2014-10-12 07:16:07

回答

0

迭代文件会产生线条。每行包含换行符。使用str.rstripstr.strip

地带换行符:

with open('names.txt') as f: 
    for line in f: 
     a = 'cp ' + line.rstrip() + ' /root/dest1' 
     # a = 'cp {} /root/dest1'.format(line.rstrip()) 
     print a 
     os.system(a) 

如果使用shutil.copy,你并不需要使用os.system

import shutil 

with open('names.txt') as f: 
    for line in f: 
     shutil.copy(line.rstrip(), '/root/dest1')