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()
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()
python read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
how to write to a text file in python
#the way i learned it
#plus explanations
from sys import * #this is for making it more flexible
#so now we gotta open a file to write in
f = open("haha.txt", "w") # the w means WRITING
#now we gotta write something
f.write(str(argv[1])) # the str means change it into a string of letters
#argv[1] means it's the thing you type after the python run thing
#for example: "python run.py helo"
#now we gotta finish it
f.close()
#if you want to see whats in it...
f = open("haha.txt", "r") #r means READING
print(f.read()) # this prints what you wrote
#example input and output
# python run.py helo
# helo
python write to file
with open(filename,"w") as f:
f.write('Hello World')
python write to file
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first filen")
f.write("This filenn")
f.write("contains three linesn")
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
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us