首页 > 解决方案 > 映射到 os.rename 多个文件

问题描述

我有这样的程序

#+begin_src ipython :session alinbx :results output
import os
import glob
import copy

fs = os.listdir()
fs = filter(lambda x: not x.endswith("org"), fs)
fsc = copy.deepcopy(fs)
print(list(fsc)[:5])
# map(lambda x: os.rename(x, f"{x}.org"), fs)
#+end_src

#+RESULTS:
: ['19.Pseudo-Terminals', '12.Thread-Control', '05.Standard-IO-Library', '07.Process-Environment', '03.File-IO']

稍后,将 org 添加到名称中

#+begin_src ipython :session alinbx :results output
map(lambda x: os.rename(x, x+'.org'), fs)
! ls | head -n 5
#+end_src

#+RESULTS:
: 00.Preface.org
: 01.UNIX-System-Overvie
: 01.xhtml
: 02.UNIX-Standardization-and-Implementations
: 03.File-IO

它不起作用,因此 for 循环有效

#+begin_src ipython :session alinbx :results output
for f in fs:
    os.rename(f, f"{f}.org")
! ls | head -n 5
#+end_src

#+RESULTS:
: 00.Preface.org
: 01.UNIX-System-Overview.org
: 01.xhtml.org
: 02.UNIX-Standardization-and-Implementations.org
: 03.File-IO.org

别说python不欣赏函数式编程,是什么原因map不工作?

标签: python-3.x

解决方案


您需要使用 map 返回的迭代器。尝试

list(map(lambda x: os.rename(x, x+'.org'), fs))

推荐阅读