Python Forum
Reading a file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Reading a file (/thread-39086.html)



Reading a file - JonWayn - Dec-30-2022

I have got a simple file read code and I need to understand why it works the way it does.

def ReadFileContents(file_path):
    try:
        with open(file_path,'r', newline='') as f:
            contents = f.read().splitlines()
            return contents
    except Exception as e:
        print(f'{e}  --  ReadFileContents')
If I run it like this: print(ReadFileContents(pth)), I get the desired result, a list of the single date entry in the file: ['12/25/2022'].
Also, running print(ReadFileContents(pth)[0]) gives me the first and only item of the list, 12/25/2022.
However running, print(ReadFileContents(pth)[:-1]), I get the undesirable result, an empty list, []. I understand this splicing to mean, start with the first item of the list and return up to the last item. Why then does it return an empty list?
Thank you for any clarification


RE: Reading a file - Gribouillis - Dec-30-2022

In a list slice, such as mylist[a:b], the item at index b is not included in the result.
>>> mylist = ['a', 'b', 'c']
>>> mylist[0:1]
['a']
>>> mylist[0:-1]
['a', 'b']
>>> mylist[:]
['a', 'b', 'c']



RE: Reading a file - perfringo - Dec-30-2022

ninjad by Gribouillis Smile

Slice value at end is 'first to be excluded'. So you basically say: give me whole list except last item. As your list happens to have only one item (which is also a last item) you get the empty list.


RE: Reading a file - ibreeden - Dec-30-2022

(Dec-30-2022, 08:35 AM)JonWayn Wrote:
print(ReadFileContents(pth)[:-1]
If you want the last item, you should not use the colon, but:
print(ReadFileContents(pth)[-1]