Reputation: 9
# create two new files
a = open("file.txt","w+")
b = open("file2.txt", "w+")
#write to file
a.write("text in english")
b.write("text in english2")
#read the file & print the text to console
teksts1 = a.read()
teksts2 = b.read()
print(teksts1)
print(teksts2)
#close both files, so we don't run into problems
a.close
b.close
I'm probably blind for not seeing the problem here, but for some reason it doesn't output anything. Its like the file is empty or something, however they are not.
Upvotes: 1
Views: 1236
Reputation: 63
After writing close it and reopen it in the mode of reading
# create two new files
a = open("file.txt","w+")
b = open("file2.txt", "w+")
#write to file
a.write("text in english")
b.write("text in english2")
a.close()
b.close()
a = open("file.txt","r")
b = open("file2.txt", "r")
#read the file & print the text to console
teksts1 = a.read()
teksts2 = b.read()
print(teksts1)
print(teksts2)
#close both files, so we don't run into problems
a.close()
b.close()
Upvotes: 0
Reputation:
Alternatively, to Hoenie's answer, close the files and open them again in read-only mode:
# create two new files
a = open("file.txt","w+")
b = open("file2.txt", "w+")
#write to file
a.write("text in english")
b.write("text in english2")
#close the files and re-open again
a.close()
b.close()
a = open("file.txt","r")
b = open("file2.txt", "r")
#read the file & print the text to console
teksts1 = a.read()
teksts2 = b.read()
print(teksts1)
print(teksts2)
#close both files, so we don't run into problems
a.close()
b.close()
Upvotes: 0
Reputation: 816
You could try this which uses with open
as opposed to open
which is a safer way of opening files:
file_list = ['file.txt', 'file2.txt']
for file in file_list:
with open(file, 'w+') as f:
f.write('text in english')
f.seek(0)
print(f.read())
This allows you to create multiple files and write to them with identical strings.
You have to seek to the first position in the file once written to read in the same open, otherwise you're at the end of the file and there's nothing to read.
Upvotes: 2
Reputation: 2600
You need to go back to the beginning of the file if you want to read text immediately after writing.
a = open("file.txt","w+")
b = open("file2.txt", "w+")
#write to file
a.write("text in english")
b.write("text in english2")
#read the file & print the text to console
a.seek(0) # go to beginning of file
b.seek(0) # go to beginning of file
teksts1 = a.read()
teksts2 = b.read()
print(teksts1)
print(teksts2)
# Close both files, so we don't run into problems
# Actually close the files. OP Forgot to call the function.
a.close()
b.close()
Upvotes: 1