不要小看这段代码哦。我还从中收获不少呢。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
os
import
string
dirName
=
"./code/demo/"
li
=
os.listdir(dirName)
for
filename
in
li:
newname
=
filename
newname
=
newname.split(
"."
)
if
newname[
-
1
]
=
=
"txt"
:
newname[
-
1
]
=
"html"
newname
=
string.join(newname,
"."
)
filename
=
dirName
+
filename
newname
=
dirName
+
newname
os.rename(filename,newname)
print
newname,
"updated successfully"
|
如果你这样写:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
os
import
string
dirName
=
"./code/demo/"
li
=
os.listdir(dirName)
for
filename
in
li:
#newname = filename
newname
=
newname.split(
"."
)
newname
=
filename
#在这后面修改newname也直接修改了filename
if
newname[
-
1
]
=
=
"txt"
:
newname[
-
1
]
=
"html"
newname
=
string.join(newname,
"."
)
filename
=
dirName
+
filename
newname
=
dirName
+
newname
os.rename(filename,newname)
print
newname,
"updated successfully"
|
因为python里面对传值和引用传值有非常诡异的“搞法”
如果函数收到的是一个可变对象(比如字典或者列表)的引用,就能修改对象的原始值——相当于通过“传引用”来传递对象。如果函数收到的是一个不可变对象(比如数字、字符或者元组)的引用,就不能直接修改原始对象——相当于通过“传值'来传递对象。
1
2
3
4
5
6
|
files
=
os.listdir(
"."
)
for
filename
in
files:
li
=
os.path.splitext(filename)
if
li[
1
]
=
=
".html"
:
newname
=
li[
0
]
+
".htm"
os.rename(filename,newname)
|