Read the file with python and delete the line breaks [Notes on reading the file]

When I tried to remove the line breaks in the file using python, I got stuck because I didn't understand the specifications for reading the file. This article is more about "reading a file" than "erasing line breaks". I'm not sure if this method is good because it is written by a python beginner. Please read it for reference only.

Wrong example

First I will give you the wrong example.

test1.py


#!/usr/bin/env python                                                           
#coding:utf-8                                                                   

f = open('test1.txt','r')

for line in f:
    text = line.replace('\n','')
    text = text.replace('\r','')
    print text,

f.close()

What if I do this?

Execution result test test

I should have replaced the line feed code with an empty string, but there was a space. This is because ~~ ** is processing line by line, so ** is doing the same thing as the code below ~~. (There seems to be a way to erase blanks even if processing is performed line by line from the comment, so there seems to be a method to process line by line. (Corrected on 6/15))

space.py


#!/usr/bin/env python                                                           
#coding:utf-8
                                                                   
print 'test',
print 'Tesuto',
print 'test'

Line breaks can be removed by , at the end of the sentence, but spaces are also inserted in this case.

In the case of python, if you process each line, a space will be inserted for each process even if it is not in the text.

Solution

To solve this, let's read and process all the files instead of line by line. Use read () to read the entire file.

test2.py


#!/usr/bin/env python                                                           
#coding:utf-8                                                                   

f = open('test1.txt','r')
Allf = f.read()

text = Allf.replace('\n','')
text = text.replace('\r','')
print text,

f.close()

Execution result test test

I was able to safely take line breaks and spaces.

Precautions other than code

If you do not enter # coding: utf-8 at the beginning of the line, a Syntax Error may occur when you write a line feed code in the code. If you get an error such as Non-ASCⅡ, check the declaration.

The line feed code is as follows.

system Line feed code
Linux \n
Mac \r
Windows \r\n

In many cases, you may be able to go with just \ n, but in the case of Windows etc., you need to remove \ r as well, so be careful.

Recommended Posts

Read the file with python and delete the line breaks [Notes on reading the file]
Let's read the RINEX file with Python ①
Read the file line by line in Python
Read the file line by line in Python
[Python] Read the specified line in the file
Read line by line from a file with Python
Python / numpy> Read the data file with the item name line> Use genfromtxt ()
[Implementation example] Read the file line by line with Cython (Python) from the last line
Python --Read data from a numeric data file and find the multiple regression line.
Draw a line / scatter plot on the CSV file (2 columns) with python matplotlib
Notes on HDR and RAW image processing with Python
Read the csv file with jupyter notebook and write the graph on top of it
Read the VTK file and display the color map with jupyter.
Notes on deploying pyenv with Homebrew and managing Python versions
Notes on reading and writing float32 TIFF images in python
Extract the xz file with python
Notes on Python and dictionary types
Print with python3 without line breaks
Python CSV file reading and writing
Reading and writing NetCDF with Python
Notes on using rstrip with python.
Reading and writing CSV with Python
Read a file in Python with a relative path from the program
[Python] Create a program to delete line breaks in the clipboard + Register as a shortcut with windows
Read CSV file with python (Download & parse CSV file)
Check the existence of the file with python
A memo with Python2.7 and Python3 on CentOS
[C] [python] Read with AquesTalk on Linux
Notes on doing Japanese OCR with Python
Reading and writing JSON files with Python
Download files on the web with Python
See file and folder information on python
[python] Read html file and practice scraping
[Automation] Read mail (msg file) with Python
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
Read CSV file with Python and convert it to DataFrame as it is
Compare nighttime and daytime returns on the Nikkei Stock Average with python
Install Chrome on the command line on Sakura VPS (Ubuntu) and launch Chrome with python from virtual display and selenium
How to read a CSV file with Python 2/3
File DL, byte value and delete in Python3
Notes on installing Python3 and using pip on Windows7
[Python] How to read excel file with pandas
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
Read table data in PDF file with Python
Zip-compress any file with the [shell] command to create a file and delete the original file.
Introduction to Python with Atom (on the way)
[Python3] Read and write with datetime isoformat with json
Have pandas read the zip file on the web
Archive and compress the entire directory with python
Convert the character code of the file with Python3
Reading and writing fits files with Python (memo)
I want to get the file name, line number, and function name in Python 3.4
Example of reading and writing CSV with Python
Reading, summarizing, visualizing, and exporting time series data to an Excel file with Python
[CGI] Run the Python program on the server with Vue.js + axios and get the output data
Python> Implementation that synthesizes 3 files with variable columns and outputs 3 items on each line
Template of python script to read the contents of the file
Python text reading for multiple lines and one line
I tried to touch the CSV file with Python
Install selenium on Mac and try it with python
Read and analyze arff format dataset with python scipy.io