0

The code does not returns the contents of text file, instead an empty string

a = open('myfile.txt', 'w+')
list01 = ['content from list 01 ~']
list02 = ['content from list 02 ']
a.writelines(list01)
a.writelines(list02)
b = open('myfile.txt', 'r+')
c = b.readline()
print("This is c: ", c)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    Don't select 2 different python version tags, because the syntax could be different – azro Mar 11 '21 at 17:47
  • 2
    An obvious problem is that you didn't close `a` in your example. You usually should be using [`with open`](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files). – Random Davis Mar 11 '21 at 17:48
  • You may think about [accepting an answer](https://stackoverflow.com/help/someone-answers) to reward those how helped you, or at least comment to explain what's missing ;) – azro Mar 27 '21 at 11:42

2 Answers2

1

The writelines doesn't effectivly writes to the file, it stays in a buffer until you call flush of close, do this easily with a with statement that auto-closes the file at its end

with open('myfile.txt', 'w') as a:
    list01 = ['content from list 01 ~']
    list02 = ['content from list 02 ']
    a.writelines(list01)
    a.writelines(list02)

with open('myfile.txt', 'r') as b:
    c = b.readline()

print("This is c: ", c)

Also use w and r, remove the + that isn't neede in your case, reference on file modes

azro
  • 53,056
  • 7
  • 34
  • 70
0

Your code is working just by making few changes.

Instead of w+ use r+. r+ is use for read and write. No need to again open the file for reading. you can just say c = a.readline()

a = open('myfile.txt', 'r+')
list01 = ['content from list 01 ~']
list02 = ['content from list 02 ']
a.writelines(list01)
a.writelines(list02)
c = a.readline()
print("This is c: ", c)
Rima
  • 1,447
  • 1
  • 6
  • 12