os.path.join()返回一个文件路径的字符串,并用正确的路径分隔符分开(Windows下是\\,Linux和OS X系统是/)1
2
3import os
os.path.join('C:','desktop','untitled')
'C:desktop\\untitled'利用
os.getcwd()可以获得当前工作路径的字符串,并可以用os.chdir()来改变这个字符串1
2
3
4
5os.getcwd()
'C:\\Program Files\\Sublime Text 3'
os.chdir('C:\\Users\\26970\\Desktop\\untitled')
os.getcwd()
'C:\\Users\\26970\\Desktop\\untitled'如果要更改的路径不存在,则会返回这样的错误:
1
2
3
4os.chdir('C:\\Desktop')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'C:\\Desktop'绝对路径和相对路径:
绝对路径是从根文件夹开始的,相对路径相对于程序的当前文件夹
用
os.makedirs()可以创建新的文件夹例如:在桌面一个名为
learn的文件夹下创建一个名为test的文件夹1
2import os
os.makedirs('C:\\Users\\26970\\Desktop\\learn\\test')如果需要创建的文件夹已经存在,会返回错误。如果中间文件夹不存在,则会自动创建
1
2
3
4
5Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\26970\AppData\Local\Programs\Python\Python37-32\lib\os.py", line 221, in makedirs
mkdir(name, mode)
FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'C:\\Users\\26970\\Desktop\\learn'调用
os.path.abspath(path)将返回参数的绝对路径的字符串。这是将相对路径转换为绝对路径的简便方法。
调用os.path.isabs(path),如果参数是一个绝对路径,就返回True,如果参数是一个相对路径,就返回False。
调用os.path.relpath(path, start)将返回从 start 路径到 path 的相对路径的字符串。如果没有提供 start,就使用当前工作目录作为开始路径调用
os.path.dirname(path)将返回一个字符串,它包含 path 参数中最后一个斜杠之前的所有内容。
调用os.path.basename(path)将返回一个字符串,它包含 path 参数中最后一个斜杠之后的所有内容。如果同时需要一个路径的目录名称和基本名称,就可以调用
os.path.split(),获得这两个字符串的元组如果需要获得文件路径的每个文件夹,需要用
os.path.sep()进行分割1
2
3
4
5file='C:\\Users\\26970\\Desktop\\learn\\test\\one.txt'
os.path.split(file)
('C:\\Users\\26970\\Desktop\\learn\\test', 'one.txt')
file.split(os.path.sep)
['C:', 'Users', '26970', 'Desktop', 'learn', 'test', 'one.txt']
文件的读写操作
使用
open()来打开文件,read()方法用来返回文件中的内容(作为一个字符串返回),使用readlines()作为字符串列表返回1
2
3
4
5
6File=open('C:\\Users\\26970\\Desktop\\learn\\hello.txt')
File.read()
'Hello World!'
File=open('C:\\Users\\26970\\Desktop\\learn\\hello.txt')
File.readlines()
['Hello World!']将
w作为第二个参数传递给open(),以写模式打开该文件,在该模式下,写入的文本将覆盖原文本将
a作为第二个参数传递给open(),以添加模式打开文件,该模式下,文本不会覆盖源文件,而是在原文件的末尾添加新的文本返回值为写入的字符个数,包括换行符
1
2
3
4
5
6
7
8
9
10
11
12
13
14File=open('C:\\Users\\26970\\Desktop\\learn\\test.txt','w')
File.write('Hello World!')
12
File.close()
File=open('C:\\Users\\26970\\Desktop\\learn\\test.txt','a')
File.write('\n你好!')
4
File.close()
test=open('C:\\Users\\26970\\Desktop\\learn\\test.txt')
puts=test.read()
test.close()
print(puts)
Hello World!
你好!