Catalogue
Reading File Contents in Python

Reading File Contents in Python

🌐 日本語で読む

Overview

This is a memo summarizing how to load the contents of a file in Python 3.

Preparing the File Used for Testing

1
2
3
4
5
6
7
8
9
cat <<EOF> sample.txt
greeting:
ja: こんにちは
en: hello

sports:
ja: 相撲
en: バスケット
EOF

Reading the File Contents

1
2
3
4
with open("sample.txt", "r") as file:
d = file.read()

print(d)
1
2
3
4
5
6
7
greeting:
ja: こんにちは
en: hello

sports:
ja: 相撲
en: バスケット

Reading Only the First Line of the File

1
2
3
4
with open("sample.txt", "r") as file:
d = file.readline()

print(d)
1
greeting:

Reading the File Line by Line

1
2
3
4
with open("sample.txt", "r") as file:
d = file.readlines()

print(d)
1
['greeting:\n', '  ja: こんにちは\n', '  en: hello\n', '\n', 'sports:\n', '  ja: 相撲\n', '  en: バスケット\n']

Reading the File and Parsing It as YAML

1
pip install pyyaml
1
2
3
4
5
6
7
8
import yaml

with open("sample.txt", "r") as file:
d = yaml.safe_load(file)

print(d)
print('---')
print(d['greeting']['ja'])
1
2
3
{'greeting': {'ja': 'こんにちは', 'en': 'hello'}, 'sports': {'ja': '相撲', 'en': 'バスケット'}}
---
こんにちは

That’s all.
I hope you find this helpful.

Author

Kenzo Tanaka

Posted on

2023-07-21

Licensed under