Python - Python 操作文件
1、代码及其说明
if __name__ == '__main__':
# 写入文件
file = open('C://Users//A-PC//Desktop//1.txt', 'w')
file.write('Good')
file.write('Good - ')
file.write('\nGood - ')
file.close()
# 读取文件
file = open('C://Users//A-PC//Desktop//1.txt')
value = file.read()
print(value)
file.close()
# 读取一行
file = open('C://Users//A-PC//Desktop//1.txt')
line = file.readline()
print(line)
file.close()
# 读取所有行
file = open('C://Users//A-PC//Desktop//1.txt')
line = file.readlines()
print(line)
file.close()
# 按行读取文件
file = open('C://Users//A-PC//Desktop//1.txt')
for l in file:
print(l, end='')
file.close()
输出
GoodGood -
Good -
GoodGood -
['GoodGood - \n', 'Good - ']
GoodGood -
Good -