CHAPTER 10 - PYTHON FILES



AD

10.1 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 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 more data 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

theSurfDragon.com


Python Navigation

Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays