Jan-01-2021, 02:31 AM
Hi,
I've got a simple code which should open, read, write, and append code. On the 3rd block of code, it returns the text from the 2nd block on the same line as the 3rd. How do I get the appended text to print on the line below it in the txt file? I'm just looknig for a carriage return (I think), but I tried in the 3rd block using this line, but it didn't do what I wanted:
Code 1
I've got a simple code which should open, read, write, and append code. On the 3rd block of code, it returns the text from the 2nd block on the same line as the 3rd. How do I get the appended text to print on the line below it in the txt file? I'm just looknig for a carriage return (I think), but I tried in the 3rd block using this line, but it didn't do what I wanted:
file.write("[b]\r[/b]This is the *Appended* text written to the file.")
Code 1
file = open("demo.txt", 'r') # (which file to open, mode) Mode means what you're doing to the file (e.g. write or read) #'w' = write to file, 'r' = read file #read file which you've opened content = file.read() #after reading file, it must safe the content, e.g. in a variable, 'content' #content = file.readline() # this will only read the first line of the txt #content = file.read(10) # this will read only the first 10 bytes (characters) of the code print(content) # print what was read # after opening a file, you always have to close it file.close()Code 2 - previous text in demo.txt file will be overwritten
#opens a file, and tells pgrogram that code will write to it file = open("demo.txt", "w") file.write("This is the *NEW* text written to the file.") #writes text to file file.close() #closes file file = open("demo.txt", "r") #opens file, tells program it will write to it content = file.read() #reads file, returns info to var 'content' print(content) #prints var content file.close() #closes fileCode 3 - previous text in demo.txt file will appended, so it won't get text deleted
#opens a file, and tells pgrogram that code will write to it file = open("demo.txt", "a") file.write("This is the *Appended* text written to the file.") #writes text to file, won't delete previous file.close() #closes file file = open("demo.txt", "r") #opens file, tells program it will write to it content = file.read() #reads file, returns info to var 'content' print(content) #prints var content file.close() #closes file