Python写入文件
请注意,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)
正常写入的文本是不会自动加换行符的,需手动添加。
如:
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!\n")
file1.write("this is second line.\n")
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!\n")
file1.write("this is second line.\n")
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!\n")
file1.write("this is second line.\n")
file1.close()
print("写入完成")
with open('test6.txt') as file2:
print("文件内容:")
for line in file2:
print(line)