0
Q:

python create file

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, "a+") as f:
  f.write('Hello World')
17
file = open("text.txt", "w") 
file.write("Your text goes here") 
file.close() 
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
16
def save_to_file(content, filename):
    with open(filename, 'w') as file:
        file.write(content)

import file_operations
file_operations.save_to_file('my_content', 'data.txt')
5
with open(filename,"w") as f:
  f.write('Hello World')
15
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
f = open("data.txt", "a")
f.write("a b c")
f.close()

f = open("data.txt", "r")
print(f.read()) 
3
# "with" closes file for you after use, even if error encountered
# r - read, w - write, rb - read binary, wb - write binary

with open('dog_breeds.txt', 'r') as reader:
     # Read and print the entire file line by line
     for line in reader:
         print(line, end='')
8
	f= open("guru99.txt","w+")
2

New to Communities?

Join the community