file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
# using 'with' block
with open("xyz.txt", "w") as file: # xyz.txt is filename, w means write format
file.write("xyz") # write text xyz in the file
# maunal opening and closing
f= open("xyz.txt", "w")
f.write("hello")
f.close()
# Hope you had a nice little IO lesson
with open(file_path+file_name*, 'wb') as a:
a.write(content)
# *example: r"C:UsersuserDesktophello_world.docx".
# 'hello_world' DOENT EXIST at the moment, python will automatically create it for us
'''
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()
my_file = open("C:UsersPythonfile.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
def write_file(Content):
f = open("logs.txt", "w") // Open the file to write the logs
f.write("
" + Content) // Write the list_user to the log_user.txt file
f.close() // Close the file
# Opening a file
file1 = open('SofthuntFile1.txt', 'w')
multiple_string = ["This is Mango
", "This is Apple
", "This is Banana
"]
single_string = "Hi
"
# Writing a string to file
file1.write(single_string)
# Writing multiple strings at a time
file1.writelines(multiple_string)
# Closing file
file1.close()
# Checking if the data is written to file or not
file1 = open('SofthuntFile1.txt', 'r')
print(file1.read())
file1.close()