|
・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.])
|
|