Mv  Log
0
Q:

python how to make a file to write to

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() 
36
with open(filename,"w") as f:
  f.write('Hello World')
15
# Basic syntax:
file_object = open("filename", "mode")
file_object.write("Data to be written")
file_object.close() 

# Example usage:
file_object = open("/path/to/my_filename.txt", "w") # w = write, r = read
file_object.write("Line of text to write")
file_object.close()
3
path = "guide/README.txt" # The path of your file should go here
with open(path, "w") as fil: # Opens the file using 'w' method. See below for list of methods.
  fil.write("This is the README. It is reccomended that you read it.") # Writes to the file used .write() method
  fil.close() # Closes file
'''
List of methods:
w* - replace everything with needed text
r^ - read the file
a* - adds to file
x - creates file

* Creates file if the file at that path does not exist
^ Throws error if file does not exist
'''
 
3
# 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
1
with open("test.txt",'w',encoding = 'utf-8') as f:
   f.write("my first file\n")
   f.write("This file\n\n")
   f.write("contains three lines\n")
1

  f = open("demofile2.txt", "a")
f.write("Now the file has more content!")

  f.close()

#open and read the file after the appending:
f = 
  open("demofile2.txt", "r")
print(f.read()) 
0
# open a file you can use the function open
file = open("myFile.txt", "w")
#here we have "open", and that's the main function
# that opens the file, next we have 2 arguments
# FILENAME and OPENING MODE
# in the filename argument you just have to write the file's location
# or if the script is in that location just write the filename
# in the opening mode you have to write in which mode you want
# to open your file, i'll list some here:
# "w" for writing to a file
# "r" for reading to a file
# "r+" for both reading and writing
# "a" to append to a file
#to write to the file use "file.write"
file.write("This has been written by a program")
#and finally to close the file when you're done with it
file.close()
# hope this helped and remember that in "w" mode it
#deletes the content of the file and replaces
# it with a new one, if you want to add something
# to a file use "a" mode
0

New to Communities?

Join the community