Python Learning - Section 09 Write File Using Command Prompt
file = open("test.py" , "w")
file.write("hello")
file.close()
You can write a file like this :
w - write
a - append
r - read
This will create the file "text.py" will have one line of text to have multiple lines , use the \n character inside the write function can ,
f.write("hello world \n")
f.write("video count \n")
To make python add(append) to a file, change the parameter when opening from
fopen("filename.txt" , "w")
to,
fopen("filename.txt" , "a")
Any line written to the file will then be added to the bottom
Recommended by LinkedIn
fobj = open("testfile.txt" , "r")
print(fobj.readlines())
fobj.readlines()
or,
with open("testfile.txt") as f :
print(f.readlines())
To read a file, change the parameter to "r"
use this line to open a file,
fobj = open("filename.txt" , "r")
Then you can read the data with
lines = fobj.readlines()
Finally, close the file
fobj.close()
Write variable to file
x = [3,4,5,1,3,84,3,2,11]
file = open("testfile.txt" , "w")
for element in x :
file.write(str(element) + ",\n")
file.close()