Opening a file with Python we need to close it as well.
# Open a new file object for writing onlymyfile =open("/tmp/newfile.txt", "w")# Use the write method to add data to the filemyfile.write("Here is my message.\n")# The "\n" must be added to separate lines on the filemyfile.write("Here is my second message.")# We must close out the file object in order to properly close the objectmyfile.close()
Instead, we can use a with codeblock which will automatically handle closing the file once we're done with it.
withopen("/tmp/newfile.txt", "r")as myfile:for line in myfile:print(line)withopen('/tmp/cars.txt', 'r')as cars:print(cars.read())
We can read all lines of a file into a list for easy use. We need to strip the newline as well.
deffileList(file):withopen(file)as f: lines = f.readlines() clean = [ line.strip()for line in lines ]return clean