creating file in python code example

Example 1: python write to 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()

Example 2: python write file

with open("file.txt", "w") as file:
  for line in ["hello", "world"]:
    file.write(line)

Example 3: python write to file

# 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

Example 4: python open and read file with

with open('pagehead.section.htm','r') as f:
    output = f.read()

Example 5: python create file

f= open("guru99.txt","w+")