代码想复制文件夹下的 .md 文件到另一个文件夹中
import os
def copy_file ( dirname ):
"""Copy .md file in a given directory and its subdirectories.
"""
for root, dirs, file in os.walk ( dirname ):
for f in file:
if os.path.splitext (root+f )[1] == ".md":
os.system ("cp %s ~/file/"%os.path.join ( root, f ))
copy_file ('.')
可是因为文件名带空格,报这样的错误,请问有什么好的处理方法呢?
cp: cannot stat ‘./Chapter ’: No such file or directory
cp: cannot stat ‘ 01 ’: No such file or directory
cp: cannot stat ‘ Best ’: No such file or directory
cp: cannot stat ‘ Friends/from-morse-to-binary.md ’: No such file or directory
cp: cannot stat ‘./Chapter ’: No such file or directory
cp: cannot stat ‘ 02 ’: No such file or directory
cp: cannot stat ‘ Code ’: No such file or directory
1
lianyue 2015-08-29 15:33:11 +08:00
空格转发成% 20 试试
|
2
lianyue 2015-08-29 15:33:20 +08:00
转换
|
3
ratazzi 2015-08-29 15:45:03 +08:00 1
我能吐槽这 Python 的用法吗,为什么不用自带模块还要去调用命令,而且还是写在循环里
|
4
loading 2015-08-29 15:45:46 +08:00 via Android
转义
顺便把+号也处理了,我前阵子也是写文件系统相关的东西! |
5
Sylv 2015-08-29 15:57:15 +08:00 via iPhone 1
文件名加引号:
"cp '%s' ~/file/" 不过还是用 Python 来复制吧,你这样有点多此一举。 |
6
loading 2015-08-29 16:11:15 +08:00 via Android
看到楼主用 os.path 想必是没找到 os.copy
其实是 shutil.copy |
7
zeroday OP @Sylv 谢谢,文件名加引号真的成功了。
我试着用 python shutil.copyfile 进行复制 filename = os.path.join (root, f ) shutil.copyfile (filename, "~/file1/%s"%f ) 提示错误。 ``` Traceback (most recent call last ): File "walk.py", line 17, in <module> copy_file ('.') File "walk.py", line 15, in copy_file shutil.copyfile (filename, "~/file1/%s"%f ) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile with open (dst, 'wb') as fdst: IOError: [Errno 2] No such file or directory: '~/file1/from-morse-to-binary.md' ``` |
10
Sylv 2015-08-29 16:51:32 +08:00 1
@zeroday Python 是不认 ~ 的,所以你得手动写完整路径,或用 os.path.expanduser () 补全路径。
|
11
binux 2015-08-29 16:59:27 +08:00 via Android 1
第一, Python 自带 copy 调用
第二, Python 自带转义函数 非要自己手拼命令,都不知道是怎么死的 |
13
zeroday OP @binux 嗯嗯,谢谢大家的指点了。这是在大家帮助下,完善好的代码。
想将文件夹下的 aaaBbbCcc.md 的文件复制为 2014-09-%d-aaa-bbb-ccc.md import os import shutil import re def copy_file ( dirname ): """Copy .md file in a given directory and its subdirectories. """ i = 0 for root, dirs, file in os.walk ( dirname ): for f in file: if os.path.splitext (root+f )[1] == ".md": filename = os.path.join (root, f ) i += 1 list = re.sub ( r"([A-Z])", r" \1", f ).split () f = '-'.join (list ).lower () shutil.copyfile (filename, os.path.expanduser ("~/file2/2014-09-%02d-%s"%(i,f ))) copy_file ('.') |
14
lionyue 2015-08-29 17:11:14 +08:00
文件路径用双引号
|