Before you run this, I am assuming you have a newline at the end of your test.txt. This will fix "combining the second and third lines".
If you really want to use a dictionary:
dct = {}
i=0
with open("test.txt") as textfile:
for line in textfile.readlines():
mylist = line.rsplit('/',1)
dct[mylist[i]] = mylist[i+1]
sorted_dict=sorted(dct.items(), key=lambda item: item[1])
with open("test.txt", "w") as textfile:
for element in sorted_dict:
textfile.write(element[i] + '/' +element[i+1])
What you did wrong
In the first line, you name your variable List
, and in the second you access it using list
.
List = line.rsplit('/', 1)
dct = {list[i]:list[i+1]}
Variable names are case sensitive so you need use the same capitalisation each time. Furthermore, Python already has a built-in list
class. It can be overridden, but I would not recommend naming your variables list
, dict
, etc.
( list[i]
will actually just generate a types.GenericAlias
object, which is a type hint, something completely different from a list, and not what you want at all.)
You also wrote
dct = {list[i]:list[i+1]}
which repeatedly creates a new dictionary in each loop iteration, overwriting whatever was stored in dct
previously. You should instead create an empty dictionary before the loop, and assign values to its keys every time you want to update it, as I have done.
You're calling sort
in each iteration in the loop; you should only call once it after the loop is done. After all, you only want to sort your dictionary once.
You also open
the file twice, and although you close it at the end, I would suggest using a context manager and the with
statement as I have done, so that file closing is automatically handled.
My code
sorted(dct.items(), key=lambda item: item[1])
means that the sorted()
function uses the second element in the item
tuple (the dictionary item) as the 'metric' by which to sort.
`textfile.write(element[i] + '/' +element[i+1])`
is necessary, since, when you did rsplit('/',1)
, you removed the /
s in your data; you need to add them back and reconstruct the string from the element
tuple before you write
it.
You don't need + \n
in textfile.write
since readlines()
preserves the \n
. That's why you should end text files with a newline: so that you don't have to treat the last line differently.