引言
with open('test.txt') as file:
content=file.read()
print(content.rstrip())
#输出:test contents
#相对路径:
path='test.txt'
#绝对路径
path='D:/PythonExp/PythonExp1/test.txt' #使用斜杠
path='D:\\PythonExp\\PythonExp1\\test.txt' #使用反斜杠
with open(path) as file:
content=file.read()
path='test.txt'
with open(path) as file:
for line in file:
print(line)
#输出:
# test content1
# test content2
# test content3
path='test.txt'
with open(path) as file:
lines=file.readlines()
for line in lines:
print(line.rstrip())
# 输出:
# test content1
# test content2
# test content3
message="联想消费互联网服务业务"
print(message.replace('联想','Lenovo'))
#输出:Lenovo消费互联网服务业务
path='test.txt'
with open(path,'a') as file:
file.write("\nAs long as you love me.")
#文件内容:
# test content1
# test content2
# test content3
# As long as you love me.
try:
print(8/0)
except ZeroDivisionError:
print("除数不能为0!")
else: #try代码执行成功才执行的代码
pass
print('1')
#输出:
# 除数不能为0!
# 1
import json
list=[1,2,3,4,5]
path='test.txt'
with open(path,'w') as file:
json.dump(list,file)
with open(path) as file:
content=json.load(file)
print(content)
#文件中的内容:[1, 2, 3, 4, 5]
#输出:[1, 2, 3, 4, 5]
message="Near, far, wherever you are."
print(message.split())
#输出:['Near,', 'far,', 'wherever', 'you', 'are.']
参考资料:
[1] Eric Matthes. Python编程从入门到实践. 北京:人民邮电出版社, 2020.
[2]嵩天,礼欣,黄天羽. Python语言程序设计基础(第二版). 北京:高等教育出版社, 2017.
[3]Python语言程序设计,北京理工大学 嵩天