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

php中世界最好的语言
Release: 2018-04-09 10:11:18
Original
10522 people have browsed it

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template