1.文件与文件路径
在python脚本中处理文件,需要添加os模块
#!/usr/bin/python3
import os
函数 | 执行效果 |
---|---|
os.path.join() | 返回一个文件路径的字符串 |
os.getcwd() | 取得当前工作路径的字符串 |
os.chdir() | 改变路径 |
os.makedirs() | 创建新文件夹(目录) |
os.path.split() | 分割一个路径的目录名称和基本名称 |
os.path.dirname() | 获得一个路径的目录名称 |
os.path.basename() | 获得一个路径的基本名称 |
os.path.exists() | 检测给定的路径是否存在 |
os.path.isfile() | 检测是否是文件 |
os.path.isdir() | 检测是否是文件夹 |
#!/usr/bin/python3
import os
print(os.getcwd())
#!/usr/bin/python3
import os
os.makedirs('/home/Scripts/Python/test')
#!/usr/bin/python3
import os
path = '/home/Scripts/Python/test'
print(os.path.split(path))
print(os.path.dirname(path))
print(os.path.basename(path))
print(os.path.isdir('/home/Scripts/Python'))
print(os.path.exists('/home/Scripts/Python/t2.txt'))
print(os.path.isfile('/home/Scripts/Python/t2.txt'))
2.文件读写过程
在python中,读写文件有3个步骤:
1.调用open()函数,返回一个File对象。
2.调用File对象的read()或write()方法
3.调用File对象的close()方法,关闭该文件
读取文件使用read()函数
#!/usr/bin/python3
import os
Wfile = open('/home/Scripts/Python/t2.txt')
Content = Wfile.read()
print(Content)
Wfile.close()
将’w’作为第二个参数传递给 open(),'a’作为第二个参数传递给 open()
open(‘t1.txt’, ‘w’) | 写模式将覆写原有的文件 |
---|---|
open(‘t1.txt’, ‘a’) | 添加模式将在已有文件末尾添加文本 |
#!/usr/bin/python3
import os
Wfile = open('/home/Scripts/Python/t2.txt','w')
Wfile.write('Hello World!\n')
Wfile.close()
#!/usr/bin/python3
import os
Wfile = open('/home/Scripts/Python/t2.txt','a')
Wfile.write('Hello World!\n')
Wfile.close()
注意: write()方法不会像 print()函数那样,在字符串的末尾自动添加换行字符。必须自己添加该字符\n。