How to use read, readline, and readlines (python) Read a csv file



Python
library
pip

MeCab

Common
class

pickle

read/readline

numpy
asfarray

digitize

expit

linalg.solve

meshgrid

mgrid

ndmin

pad

poly1d

polyfit

prod

shape

matplotlib
figure

pcolormesh

scatter

pytorch
BCELoss, MSELoss

device

Embedding

TensorDataset, Dataloader

RNN, LSTM
scikit-learn
SVC

GaussianNB

scipy
interpolate
tkinter
postscript

image display

frame, grid

Crop Image

other
linear interpolation

Hysteresis switch

Square/Triangle wave

OpenAI gym
CartPole-v0

By purpose
1 of K Coding


Release date:2024/12/22         

In Japanese


■Description
Reads text, csv, and other files. Note that csv.reader may be easier to use.

■Example: Reading a csv file
The following test.csv file will be used as the subject.



<read:Read everything as a string>

with open("test.csv", "r") as file: # r means read only
    data = file.read()

data # If I use print(data), the output looks different, so I'll output it as data

    → '4,5,7,1\n2,5,6,7\n3,9,10,11\n'

data[0] # Specify the 0th character

    → '4'

data[0:4] # Specify the 0th to 5th characters. The comma is counted as one character.

    → ',5,7'


<readline:Read only one line as a string>

with open("test.csv", "r") as file:
    data = file.readline()

data

    → '4,5,7,1\n'


<readlines:Read everything as a string and make a list>

with open("test.csv", "r") as file:
    data = file.readlines()

data

    → ['4,5,7,1\n', '2,5,6,7\n', '3,9,10,11\n']

data[1] # Specify the first list

    → '2,5,6,7\n'


class=bor><Convert strings to numbers>
You can convert them to numbers using numpy. We will continue to use the above result.

data[1].split(',') # split separates data with any character.

   → ['2', '5', '6', '7\n']

import numpy as np
np.asfarray(data[1].split(','))

    → array([2., 5., 6., 7.])










List of related articles



Python
library
pip

MeCab

Common
class

pickle

read/readline

numpy
asfarray

digitize

expit

linalg.solve

meshgrid

mgrid

ndmin

pad

poly1d

polyfit

prod

shape

matplotlib
figure

pcolormesh

scatter

pytorch
BCELoss, MSELoss

device

Embedding

TensorDataset, Dataloader

RNN, LSTM
scikit-learn
SVC

GaussianNB

scipy
interpolate
tkinter
postscript

image display

frame, grid

Crop Image

other
linear interpolation

Hysteresis switch

Square/Triangle wave

OpenAI gym
CartPole-v0

By purpose
1 of K Coding