关于Python的一些问题和记录
# 一、在指定的文件夹下执行命令
import os
import subprocess
## 方法1
subprocess.check_call('执行的命令', cwd='指定的目录下')
## 方法2
os.system('cd 指定的目录 && 执行的命令')
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 二、目录操作
# 创建目录
os.mkdir("file")
# 复制文件:
shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
# 复制文件夹:
shutil.copytree("olddir","newdir") #olddir和newdir都只能是目录,且newdir必须不存在
# 重命名文件(目录)
os.rename("oldname","newname") #文件或目录都是使用这条命令
# 移动文件(目录)
shutil.move("oldpos","newpos")
# 删除文件
os.remove("file")
# 删除目录
os.rmdir("dir") #只能删除空目录
shutil.rmtree("dir") #空目录、有内容的目录都可以删
# 转换目录
os.chdir("path") #换路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 三、Python2 中文输出乱码
# 1. 开头声明
#!/usr/bin/env python
# 注意开头加上这句编码声明注释 或 "# encoding:utf-8"
# 只要满足正则表达式^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)就OK。
# -*- coding: utf-8 -*-
1
2
3
4
5
2
3
4
5
# 2. 中文用unicode表示
只要在中文前面加上个小u
标记,后面的中文就用unicode
存储了。
# encoding:utf-8
s = u"中文"
# 或者
# s = '中文'.decode("utf-8")
if PYVER == 2:
decodeU = originStr.decode("utf-8")
shell_color.printSkyBlue(decodeU.encode('gb2312'))
print s
print repr(s)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 3. 再进行gbk
或gb2312
编码
# encoding:utf-8
s = raw_input(u"请输入中文汉字:".encode('gb2312'))
# 或者
# s = input("请输入中文汉字:".decode("utf-8").encode('gb2312'))
print s
print type(s)
print repr(s)
1
2
3
4
5
6
7
2
3
4
5
6
7
# 4. 总结
- 文件存储为
utf-8
格式,编码声明为utf-8
,# encoding:utf-8
- 出现汉字的地方前面加
u
- 不同编码之间不能直接转换,要经过
unicode
中间跳转 cmd
下不支持utf-8
编码
# 四、多行输入
# 多行输入
stopWord = 'endl' # 修改输入终止符为空行
message = ''
print('输入' + "'" + stopWord + "'"+ "结束")
for line in iter(input, stopWord):
message += line
print("提交备注" + message)
1
2
3
4
5
6
7
2
3
4
5
6
7