Input / output with Python (Python learning memo ⑤)

Output format

point

s = 'Hello, world.'
print(str(s))
# Hello, world.
print(repr(s))
# 'Hello, world.'
print(str(1/7))
# 0.14285714285714285

x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
# The value of x is 32.5, and y is 40000...

#String repr()Returns string quotes and backslashes as is
hello = 'hello, world\n'
hellos = repr(hello)
print(hellos)
# 'hello, world\n'

#Every Python object is a repr()Can be converted with
print(repr((x, y, ('spam', 'eggs'))))
# (32.5, 40000, ('spam', 'eggs'))

rjust()Right justification using


for x in range(1, 11):
    print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
    print(repr(x*x*x).rjust(4))

#output
#  1   1    1
#  2   4    8
#  3   9   27
#  4  16   64
#  5  25  125
#  6  36  216
#  7  49  343
#  8  64  512
#  9  81  729
# 10 100 1000

Right justification using format



for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))

#output
#  1   1    1
#  2   4    8
#  3   9   27
#  4  16   64
#  5  25  125
#  6  36  216
#  7  49  343
#  8  64  512
#  9  81  729
# 10 100 1000

print('12'.zfill(5))
# 00012

print('-3.14'.zfill(7))
# -003.14

print('3.14159265359'.zfill(5))
# 3.14159265359

Various formats


#in format{}use
print('Happy birth day {} !, You are {} years old now !'.format('Kawauso', '5'))
# Happy birth day Kawauso !, You are 5 years old now !

#Argument numbering
print('Happy birth day {0} !, You are {1} years old now !'.format('Kawauso', '5'))
# Happy birth day Kawauso !, You are 5 years old now !

#Keyword argument specification
print('Happy birth day {name} !, You are {year} years old now !'.format(name='Kawauso', year='5'))
# Happy birth day Kawauso !, You are 5 years old now !

#Mixed number and keyword arguments
print('Happy birth day {0} !, You are {year} years old now !'.format('Kawauso', year='5'))
# Happy birth day Kawauso !, You are 5 years old now !

#float type notation
print('Happy birth day {name} !, You are {year:3f} now !'.format(name='Kawauso', year=5))
# Happy birth day Kawauso !, You are 5.000000 now !

#When r is used, repr()Is applied
print('Happy birth day Kawauso !, You are {!r} now !'.format(5.12345678))
# Happy birth day Kawauso !, You are 5.12345678 now !

#Notated with 3 digits after the decimal point
import math
print('Pi is about{0:.3f}Is'.format(math.pi))
#Pi is about 3.142

# %How to specify using
print('Pi is about%5.3f' % math.pi)
#Pi is about 3.142

# :You can specify the minimum width of the number of characters in the field by passing an integer after
table = {'kawauso': 100, 'mando': 200, 'banjo': 300}
for name, num in table.items():
    print('{0:10} ==> {1:10d}'.format(name, num))

# kawauso    ==>        100
# mando      ==>        200
# banjo      ==>        300

#Pass the dict[]It is convenient to access by name because you can specify it with
print('kawauso: {0[kawauso]:d}; mando: {0[mando]:d}; ' 
    'banjo: {0[banjo]}'.format(table))
# kawauso: 100; mando: 200; banjo: 300

# **You can do the same by passing it as a keyword argument using notation
print('kawauso: {kawauso:d}; mando: {mando:d}; ' 
    'banjo: {banjo}'.format(**table))
# kawauso: 100; mando: 200; banjo: 300

Reading and writing files

open()

f = open('file', 'w')

File object method

Operate on this text file

workfile


The first line
2nd line
3rd line

f.read()

f = open('workfile', 'r')
print(f.read())
#output
#The first line
#2nd line
#3rd line
f.close()

f.readline()

print(f.readline())
print(f.readline())

#output
#The first line
#
#2nd line
for line in f:
    print(line, end='')

#output
#The first line
#
#2nd line
#
#3rd line
    
# f.write('4th line')
# print(f.read())

f.readlines()

print(f.readlines())

#output
# ['The first line\n', '2nd line\n', '3rd line']

f.write()

print(f.write('4th line'))

#output
# 3

f.tell()

f.seek (offset, starting point)

f = open('workfile', 'rb+')
print(f.write(b'0123456789abscef'))
# 16
print(f.seek(5))
# 5
print(f.read(1))
# b'5'
print(f.seek(-3, 2))
# 16
print(f.read(1))
# b's'

f.close()

Use with when working with files

with open('workfile', 'r') as f:
    read_data = f.read()

print(f.closed)
# True

Convert object to json string and save to file

point

import json
x = [1, 'kawasuo', 'list']

print(json.dumps(x))
# [1, "kawasuo", "list"]

with open('sample.json', 'w') as f:
    # sample.Write to json
    json.dump(x, f)

with open('sample.json', 'r') as f:
    # sample.Read from json
    print(json.load(f))
    # [1, "kawasuo", "list"]

Recommended Posts

Input / output with Python (Python learning memo ⑤)
python learning output
"Scraping & machine learning with Python" Learning memo
Python class (Python learning memo ⑦)
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python
Python module (Python learning memo ④)
Learning Python with ChemTHEATER 05-1
python input and output
Learning Python with ChemTHEATER 02
Python audio input / output
Learning Python with ChemTHEATER 01
Twitter graphing memo with Python
Try Python output with Haxe 3.2
Reinforcement learning starting with Python
Machine learning with Python! Preparation
Beginning with Python machine learning
Python Iteration Learning with Cheminformatics
Python control syntax, functions (Python learning memo ②)
Matrix representation with Python standard input
Python memo
Tips on Python file input / output
python memo
Machine learning with python (1) Overall classification
python memo --Specify options with getopt
Output to csv file with Python
Python memo
Perceptron learning experiment learned with Python
[Note] Hello world output with python
Unit test log output with python
python memo
python learning
Python memo
Notes for Python file input / output
Interval scheduling learning memo ~ by python ~
Python memo
[Memo] Tweet on twitter with python
Python memo
[Examples of improving Python] Learning Python with Codecademy
Convert memo at once with Python 2to3
Data input / output in Python (CSV, JSON)
Python numbers, strings, list types (Python learning memo ①)
Memo to ask for KPI with python
Amplify images for machine learning with python
Output color characters to pretty with python
Machine learning with python (2) Simple regression analysis
"System trade starting with Python3" reading memo
Output Python log to console with GAE
A memo with Python2.7 and Python3 on CentOS
[Shakyo] Encounter with Python for machine learning
Python data structure and operation (Python learning memo ③)
UnicodeEncodeError struggle with standard output of python3
Data analysis starting with python (data preprocessing-machine learning)
Mayungo's Python Learning Episode 8: I tried input
Python standard library: second half (Python learning memo ⑨)
Python & Machine Learning Study Memo ③: Neural Network
Python & Machine Learning Study Memo ④: Machine Learning by Backpropagation
[Python] Easy Reinforcement Learning (DQN) with Keras-RL
Python & Machine Learning Study Memo ⑥: Number Recognition
Build AI / machine learning environment with Python
[Python] Chapter 02-03 Basics of Python programs (input / output)