When reading the list from the file, the function append(s) gives none



  • I used the function. open()to preserve the contents of the list:

    my_list = ['1', '2', 'a']
    

    save = open('items.txt', 'w')
    save.write(', '.join(my_list))
    save.close

    We need to add the stored data on the sheet, but using the function. append() It's a shell. None:

    my_list = []
    new = open('items.txt')

    'items.txt' has "1, 2, a" as a string.

    for item in new:
    print(my_list.append(item))

    Why is this happening?



  • append Modifies the list and doesn't bring anything back on its own.

    That's right.

    my_list = ['1', '2', 'a']
    

    with open('items.txt', 'w') as f:
    f.write(', '.join(my_list))

    with open('items.txt', 'r') as f:
    text = f.read()

    new_list = text.split(', ')
    print(new_list)

    ['1', '2', 'a']

    A little more detailed

    File work is better through. with to be automatically closed and not triggered close It is.

    You know what kind of thing. new In your example:

    type(new)

    <type 'file'>`

    Accordingly, loss of new It's gonna take back the lines of the file, not separate signs. However, the code from the question would not work in the opposite case, as the gaps and overlaps were no worse than the Python letters and figures. We'd get a list:

    ['1', ',', ' ', '2', ',', ' ', 'a']

    So the Python list is a variable data structure, append adds an element to the list and doesn't bring anything back.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2