VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python爬虫 >
  • 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)




相关教程