1、python文件的打开
在打开文件时,可以使用不同的模式来操作文件,常用的模式包括:
"r":`只读模式`,打开文件进行读取操作。
"w":`写入模式`,打开文件进行写入操作,如果文件已存在则会清空文件内容。
"a":`追加模式`,打开文件进行写入操作,如果文件已存在则在文件末尾追加内容。
"rb":以`二进制格式打开文件进行读取`操作。
"wb":以`二进制格式打开文件进行写入`操作。
1-r模式
打开文件
file=open("file.txt","r",encoding="utf-8")
读取文件内容
content = file.read()
print(content)
关闭文件
file.close()
2-w模式
打开文件进行写入操作
file=open("file.txt","w",encoding="utf-8")
写入内容到文件
file.write("Hello, World!")
关闭文件
file.close()
3-a模式
打开文件进行追加写入操作
file = open("file.txt", "a")
追加内容到文件
file.write("This is a new line.")
关闭文件
file.close()
4-rb模式
#我们使用"rb"模式打开文件"file.txt"进行二进制读取操作,并打印出文件的二进制内容。
#这种模式适用于读取包含二进制数据的文件,如图片、音频等。
打开文件进行二进制读取操作
file = open("file.txt", "rb")
读取文件内容
content = file.read()
print(content)
关闭文件
file.close()
5-wb模式
打开文件进行二进制写入操作
file = open("file.txt", "wb")
写入二进制数据到文件
data = b'\x48\x65\x6c\x6c\x6f' # 以二进制形式表示字符串"Hello"
file.write(data)
关闭文件
file.close()
2、python文件的写入
在Python中,可以使用内置的open()函数来打开文件并进行写入操作。下面是一些常见的文件写入方式:
1-写入字符串到文件:
打开文件进行写入
with open('output.txt', 'w') as file:
file.write('Hello, world!')
’
运行运行
2-写入多行内容到文件:
打开文件进行写入
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'w') as file:
file.writelines(lines)
3-使用格式化字符串写入内容:
打开文件进行写入
name = 'Alice'
age = 25
with open('output.txt', 'w') as file:
file.write(f'Name: {name}, Age: {age}\n')
4-使用追加模式写入内容:
打开文件进行追加
with open('output.txt', 'a') as file:
file.write('This is a new line.\n')
请注意,使用’w’模式打开文件会覆盖原有内容,使用’a’模式会在文件末尾追加内容。使用with语句可以确保文件操作完成后自动关闭文件。
3、python文件读取
在Python中,可以使用内置的open()函数来打开文件并进行读取操作。下面是一些常见的文件读取方式:
1-读取整个文件内容:
打开文件进行读取
with open('file.txt', 'r') as file:
content = file.read()
print(content)
2-逐行读取文件内容:
打开文件进行逐行读取
with open('file.txt', 'r') as file:
for line in file:
print(line)
3-读取指定字节数的内容:
打开文件进行读取
with open('file.txt', 'r') as file:
content = file.read(10) # 读取前10个字节
print(content)
4-使用readlines()方法读取所有行到列表:
打开文件进行读取
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line)