Home >Backend Development >Python Tutorial >How to read and write txt files line by line in python

How to read and write txt files line by line in python

php中世界最好的语言
php中世界最好的语言Original
2018-04-09 10:11:1810572browse

This time I will bring you pythonHow to read and write txt files line by line, what are the precautions for reading and writing txt files line by line in python, the following is a practical case, let's come together take a look.

The example is as follows:

# -*-coding:utf-8-*-
import os
file_obj = open("test2.txt")
all_lines = file_obj.readlines()
for line in all_lines:
  print line
file_obj.close()
# 写之前,先检验文件是否存在,存在就删掉
if os.path.exists("dest.txt"):
  os.remove("dest.txt")
mylist = ["luoluo", "taotao", "mumu"]
# 以写的方式打开文件,如果文件不存在,就会自动创建
file_write_obj = open("dest.txt", 'w')
for var in mylist:
  file_write_obj.writelines(var)
  file_write_obj.write('\n')
file_write_obj.close()

w Open in write mode,

a Open in append mode

r Open in read-write mode

w Open in read-write mode

a Open in read-write mode

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to convert a python string into a two-dimensional array

Event emitter’s listening event

The above is the detailed content of How to read and write txt files line by line in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn