2014-10-12 189 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')