【问题标题】:Script to remove all files from a text file从文本文件中删除所有文件的脚本
【发布时间】:2014-10-12 07:13:15
【问题描述】:

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

这是我的脚本:

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

谁能帮我解决这个问题。顺便说一句,我打印命令只是为了知道出了什么问题。

【问题讨论】:

  • 你想去掉变量行上的换行符

标签: python string python-2.7 file-io


【解决方案1】:

迭代文件会产生行。每行包含换行符。

使用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')

【讨论】:

    猜你喜欢
    • 2011-08-23
    • 2014-08-10
    • 1970-01-01
    • 2023-03-23
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多