file handling in python - halvorsen.blog

25
File Handling in Python Hans-Petter Halvorsen https://www.halvorsen.blog

Upload: others

Post on 01-Jan-2022

26 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: File Handling in Python - halvorsen.blog

File Handling in Python

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 2: File Handling in Python - halvorsen.blog

https://www.halvorsen.blog/documents/programming/python/

Free Textbook with lots of Practical Examples

Page 3: File Handling in Python - halvorsen.blog

Additional Python Resources

https://www.halvorsen.blog/documents/programming/python/

Page 4: File Handling in Python - halvorsen.blog

• File Handling in Python• Write Data to File• Read Data from File• Logging Data to File• Open File in Excel• Open Data in Python and Plot the Data

Contents

Page 5: File Handling in Python - halvorsen.blog

• Python IDLE• Spyder (Anaconda distribution)• PyCharm• Visual Studio Code• Visual Studio• Jupyter Notebook• …

Python Editors

Page 6: File Handling in Python - halvorsen.blog

Spyder (Anaconda distribution)

Code Editor window

Console window

Variable Explorer window

Run Program button

https://www.anaconda.com

Page 7: File Handling in Python - halvorsen.blog

• Python has several functions for creating, reading, updating, and deleting files

• The key function for working with files in Python is the open() function.

• The open() function takes two parameters; Filename, and Mode.

File Handling in Python

Page 8: File Handling in Python - halvorsen.blog

There are four different methods (modes) for opening a file:• "x" - Create - Creates the specified file, returns an error if the file exists• "w" - Write - Opens a file for writing, creates the file if it does not exist• "r" - Read - Default value. Opens a file for reading, error if the file does

not exist• "a" - Append - Opens a file for appending, creates the file if it does not

existIn addition you can specify if the file should be handled as binary or text mode• "t" - Text - Default value. Text mode• "b" - Binary - Binary mode (e.g. images)

File Handling in Python

Page 9: File Handling in Python - halvorsen.blog

Write Data to File

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 10: File Handling in Python - halvorsen.blog

To create a New file in Python, use the open() method, with one of the following parameters:• "x" - Create - Creates the specified file, returns an error if the file exists• "w" - Write - Opens a file for writing, creates the file if it does not exist• "a" - Append - Opens a file for appending, creates the file if it does not

exist

To write to an Existing file, you must add a parameter to the open()method:• "w" - Write - Opens a file for writing, creates the file if it does not exist• "a" - Append - Opens a file for appending, creates the file if it does not

exist

Write Data to File

Page 11: File Handling in Python - halvorsen.blog

Write Data to File

f = open("myfile.txt", "x")

data = "Hello World"

f.write(data)

f.close()

File Name x = Create

Page 12: File Handling in Python - halvorsen.blog

Read Data from File

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 13: File Handling in Python - halvorsen.blog

To read to an existing file, you must add the following parameter to the open() function:• "r" - Read - Default value. Opens a file for

reading, error if the file does not exist

Read Data from File

Page 14: File Handling in Python - halvorsen.blog

Read Data from File

f = open("myfile.txt", "r")

data = f.read()

print(data)

f.close()

File Name r = Read

Page 15: File Handling in Python - halvorsen.blog

Logging Data to File

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 16: File Handling in Python - halvorsen.blog

Logging Data to File

data = [1.6, 3.4, 5.5, 9.4]

f = open(”logdata.txt", "x")

for value in data:record = str(value)f.write(record)f.write("\n")

f.close()

Typically you want to write multiple data to the, e.g., assume you read some temperature data at regular intervals and then you want to save the temperature values to a File.

Logging Data to File:f = open("logdata.txt", "r")

for record in f:record = record.replace("\n", "")print(record)

f.close()

Read Logged Data from File:

Add New Line (or “Enter“)

Page 17: File Handling in Python - halvorsen.blog

Practical Examples

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 18: File Handling in Python - halvorsen.blog

Simulation and Plottingimport math as mtimport numpy as npimport matplotlib.pyplot as plt

# Model ParametersT = 5a = -1/T

# Simulation Parametersx0 = 1 t = 0tstart = 0tstop = 25increment = 1x = []x = np.zeros(tstop+1)t = np.arange(tstart,tstop+1,increment)

# Define the Functionfor k in range(tstop):

x[k] = mt.exp(a*t[k]) * x0

# Plot the Simulation Resultsplt.plot(t,x)plt.title('Simulation of Dynamic System')plt.xlabel('t')plt.ylabel('x')plt.grid()plt.axis([0, 25, 0, 1])plt.show()

Given the system (differential equation): �̇� = 𝑎𝑥The solution is given by: 𝑥 𝑡 = 𝑒!"𝑥#Where 𝑎 = − $

% 𝑇 is the time constant, 𝑇 = 5

Initial condition: 𝑥 0 = 𝑥& = 1 0 ≤ 𝑡 ≤ 25

We should add Grid, and proper Title and Axis Labels to the plot

Page 19: File Handling in Python - halvorsen.blog

Logging Simulation Dataimport math as mtimport numpy as npimport matplotlib.pyplot as plt

# Open Filef = open("simdata.txt", "w")

def writedata(t, x):time = str(t)value = str(round(x, 2))f.write(time + "\t" + value)f.write("\n")

# Model ParametersT = 5a = -1/T

# Simulation Parametersx0 = 1 t = 0tstart = 0tstop = 25increment = 1x = []x = np.zeros(tstop+1)t = np.arange(tstart,tstop+1,increment)

for k in range(tstop):x[k] = mt.exp(a*t[k]) * x0writedata(t[k], x[k])

f.close()

# Plot the Simulation Resultsplt.plot(t,x)plt.title('Simulation of Dynamic System')plt.xlabel('t')plt.ylabel('x')plt.grid()plt.axis([0, 25, 0, 1])plt.show()

Page 20: File Handling in Python - halvorsen.blog

Code Details

def writedata(t, x):time = str(t)value = str(round(x, 2))f.write(time + "\t" + value)f.write("\n")

Add New Line (or “Enter“)

A separate Function for dealing with the Writing to the File has been made. That is of course nor necessary, but the code becomes easier to read and maintain.

I guess you should always think about the code structure, because when your program grows it may become ”messy“. Also consider reuse where possible, i.e., create Functions in separate files, etc.

Add Tabulator, so the t and x will be in 2 separate columns in the file

Convert to String values

Show values with 2 Decimals

Page 21: File Handling in Python - halvorsen.blog

Open Data in Excel

Depending on your Settings in Excel, you may need to convert the Decimal Point from “.” to “,“

Page 22: File Handling in Python - halvorsen.blog

Open Data in Excel

Page 23: File Handling in Python - halvorsen.blog

Read Simulation Dataimport matplotlib.pyplot as plt

f = open("simdata.txt", "r")

t = []x = []

for record in f:record = record.replace("\n", "")

time, value = record.split("\t")

t.append(int(time)) x.append(float(value))

f.close()

# Plot the File Dataplt.plot(t,x)plt.title('Simulation of Dynamic System')plt.xlabel('t')plt.ylabel('x')plt.grid()plt.show()

Page 24: File Handling in Python - halvorsen.blog

Additional Python Resources

https://www.halvorsen.blog/documents/programming/python/

Page 25: File Handling in Python - halvorsen.blog

Hans-Petter Halvorsen

University of South-Eastern Norwaywww.usn.no

E-mail: [email protected]: https://www.halvorsen.blog