xxxxxxxxxx
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, world!")
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
xxxxxxxxxx
# Method 1
# Use context manager "with" that automatically closes connection
with open("filename.txt", "w") as file: # xyz.txt is filename, w means write format
file.write("hello") # write text xyz in the file
# Method 2
# Manually close connection
f= open("filename.txt", "w")
print(f.name) # will show what file is currently you are working with : filename.txt
print(f.mode) # will show which mode is currently in use : w
f.write("hello")
f.close()
xxxxxxxxxx
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
xxxxxxxxxx
'''
You can read and write in files with open()
'r' = read
'w' = write (overwrite)
'a' = append (add)
NOTE: You can use shortened 'file.txt' if the file is in the same
directory (folder) as the code. Otherwise use full file adress.
'''
myFile = open('file.txt', 'r') # Open file in reading mode
print(myFile.read()) # Prints out file
myFile.close() # Close file
myNewFile = open('newFile.txt', 'w') # Overwrites file OR creates new file
myNewFile.write('This is a new line') # Adds line to text
myNewFile.close()
file = open('newFile.txt', 'a') # Opens existing newFile.txt
file.write('This line has been added') # Add line (without overwriting)
file.close()
xxxxxxxxxx
my_file = open("C:\\Users\\Python\\file.txt", "w")
#Give the path accurately and use \\
my_file.write("This is the test text")
my_file.close()
# It is always recommended to close the file after modifying
# to see the output, open the file - file.txt