java中的接口是类吗
1967
2022-06-19
请注意,Python不会将数字写入文本文件,如果要将数字写入文本文件,
需要用str函数对其进行转换。
如:
num1=100000
with open('test.txt','w') as file1:
file1.write(str(num1))
file1.close()
print("写入完成")
with open('test.txt') as file2:
print("文件内容:")
for line in file2:
print(line)
Python写入文件
正常写入的文本是不会自动加换行符的,需手动添加。
如:
with open('test.txt','w') as file1:
file1.write("hello,world!")
file1.write("this is second line.")
file1.close()
print("写入完成")
with open('test.txt') as file2:
print("文件内容:")
for line in file2:
print(line)
如果想换行可以加换行符
with open('test.txt','w') as file1:
file1.write("hello,world! ")
file1.write("this is second line. ")
file1.close()
print("写入完成")
with open('test.txt') as file2:
print("文件内容:")
for line in file2:
print(line)
附加模式
如果您不想清空原有文件,可以使用附加模式。
如:
with open('test.txt','a') as file1:
file1.write("hello,world! ")
file1.write("this is second line. ")
file1.close()
print("写入完成")
with open('test.txt') as file2:
print("文件内容:")
for line in file2:
print(line)
创建一个空文件
with open(‘test6.txt‘,’w’) as file1:
file1.write("hello,world! ")
file1.write("this is second line. ")
file1.close()
print("写入完成")
with open('test6.txt') as file2:
print("文件内容:")
for line in file2:
print(line)
对行的读取和写入
可以使用方法readline,不指定参数默认读取一行并返回,指定参数为最多读取多少个字符。
要读取文件中所有的行,并以列表的方式返回它们,可以使用方法readlines。方法writelines接受一个字符串列表写入文件中。
发表评论
暂时没有评论,来抢沙发吧~