CHAPTER 13 - PYTHON FILES



AD

13.1.0 Working with Python files

In some circumstances we need to add information to text files, so here are some examples on how to handle files. Notice that myfileinfo.txt is the file created and managed. It will be displayed with your list of py programs under Project Files.

# Create a file and write the numbers 1,2,4 to it
myfile = open("myfileinfo.txt", "w")
myfile.write("1\n")   # \n is just a line return character
myfile.write("2\n")
myfile.write("4\n")
myfile.close()


# Append the number 6 to the file
myfile = open("myfileinfo.txt", "a")
myfile.write("6\n")
myfile.close()


# Read the file and print it
myfile = open("myfileinfo.txt", "r")
print(myfile.read())
myfile.close()
# Output
# 1
# 2
# 4
# 6


# Read the file a line at a time
myfile = open("myfileinfo.txt", "r")
print(myfile.readline())
print(myfile.readline())
print(myfile.readline())
print(myfile.readline())
# Output
# 1
# 2
# 4
# 6


# Read a line at a time with a loop
myfile = open("myfileinfo.txt", "r")
for x in myfile:
   print(x)
# Output
# 1
# 2
# 4
# 6


# Copy a file, import shutil module
from shutil import copyfile
copyfile('myfileinfo.txt', 'myfileinfocopy.txt')


# Rename a file using using move() method
from shutil import move
move('myfileinfocopy.txt', 'myfileinfocopyrenamed.txt')


# Remove a file using os module
import os
os.remove('myfileinfocopyrenamed.txt')


# See if a file exists using os module
import os
if os.path.exists('myfileinfo.txt'):
   print('File exists')
else:
   print('There is no such file')

# Output
# File exists





Engineering-Python

SALARSEN.COM
Table of Contents
Ch1-Install Python
Ch2-Install PyCharm
Ch3-Save Work
Ch4-Add Project
Ch5-Variables
Ch6-Print&Input
Ch7-Lists
Ch8-Loops
Ch9-If&Logical
Ch10-Functions
Ch11-Bubble Sort
Ch12-Plotting
Ch13-Files
Ch14-Print Format
Ch15-Dict&Comp&Zip
Ch16-Arrays
Ch17-Electrical
Ch18-Regression
Ch19-Differential
Ch20-Secant