For example, suppose you have the following text files in the tests directory:
articles.txt
Marble,Sleepy
White,I'm hungry
Black,Somehow warm
Marble,Poe Poe Poe
The read method gets the entire opened file as a string. \ n is included. Entering a number in the argument limits the number of characters.
with open('tests/articles.txt',encoding='utf-8') as f:
test = f.read(10)
print(test)
Then
Marble,Sleepy
Shi
Will be.
If nothing is entered in the argument, everything will be acquired.
with open('tests/articles.txt',encoding='utf-8') as f:
test = f.read()
print(test)
Then
Marble,Sleepy
White,I'm hungry
Black,Somehow warm
Marble,Poe Poe Poe
Will be.
(3)readline If you execute it as it is, only one line of the file will be read.
with open('tests/articles.txt',encoding='utf-8')as f:
test= f.readline()
print(test)
Then
Marble,Sleepy
Will be.
(4)readlines You can get the entire file as a line-by-line list.
with open('tests/articles.txt',encoding='utf-8')as f:
test= f.readlines()
print(test)
Then
['Marble,Sleepy\n', 'White,I'm hungry\n', 'Black,Somehow warm\n', 'Marble,Poe Poe Poe\n']
Will be.
Set the articles text file in the tests directory and run test.py The summary is as follows.
┬test.py
└tests
└articles.txt
articles.txt
Marble,Sleepy
White,I'm hungry
Black,Somehow warm
Marble,Poe Poe Poe
.python:test.py
with open('tests/articles.txt',encoding='utf-8') as f:
test = f.read(10)
print('\n'+'\n'+test)
print('\n--------------------------\n')
with open('tests/articles.txt',encoding='utf-8') as f:
test = f.read()
print(test)
print('\n--------------------------\n')
with open('tests/articles.txt',encoding='utf-8') as f:
test= f.readline()
print(test)
print('\n--------------------------\n')
with open('tests/articles.txt',encoding='utf-8') as f:
test= f.readlines()
print(test)
print('\n'+'\n')
Marble,Sleepy
Shi
--------------------------
Marble,Sleepy
White,I'm hungry
Black,Somehow warm
Marble,Poe Poe Poe
--------------------------
Marble,Sleepy
--------------------------
['Marble,Sleepy\n', 'White,I'm hungry\n', 'Black,Somehow warm\n', 'Marble,Poe Poe Poe\n']
Recommended Posts