-1

I am new to Python..

I have a list (names.txt) which is four names:

  • Colin
  • Gary
  • Gibby
  • Ross

I would like to output the list from the file, then change the order of the names by one space and save that output at the original "names.txt" file.

i.e.

Run1 would be: Colin Gary Gibby Ross

Run2 would be: Gary Gibby Ross Colin

Run3 would be: Gibby Ross Colin Gary

....and so on.

The code I have so far is able to take the file and output as a list, but I don't know how to move the order by 1 place and save again:

#!/usr/bin/python

# Open a file
with open ('names.txt', 'r') as f:
  list1 = f.read().splitlines()
  for item1 in list1[0:4]:
   print (item1)
f.close()

All help appreciated. Thanks.

Rajeesh Menoth
  • 1,704
  • 3
  • 17
  • 33

4 Answers4

2

This answer details how to shift a list using collections.deque which they state is optimised for "pushing and pulling on both ends" To that end, I have included the example code below for your convenience.

from collections import deque
items = deque([1, 2])
items.append(3) # deque == [1, 2, 3]
items.rotate(1) # The deque is now: [3, 1, 2]
items.rotate(-1) # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3] 
Community
  • 1
  • 1
Koga
  • 523
  • 4
  • 13
1

Just print all starting from index 1 in a loop. At the end print index 0

for i in range(1:len(list1)):
    print(list1[i])
print(list1[0])

Or if you need to have it in a new list:

list1 = list1[1:] + list1[:1]
theBugger
  • 441
  • 3
  • 14
0

You can rotate a sequence like this, using slice notation.

def rotate(sequence, shift=1):
    return sequence[-shift:] + sequence[:-shift]

>>> rotate([1, 2, 3, 4])
[4, 1, 2, 3]

>>> rotate('hello world', 5)
'o worldhell'

>>> rotate(['Colin', 'Gary', 'Gibby', 'Ross'], -1)
['Gary', 'Gibby', 'Ross', 'Colin']

This rotate function does not mutate the original sequence. For very long sequences and faster performance, you can check out collections.deque from the standard library. The deque sequence type can be rotated in-place in a memory and performance efficient way.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67
0

This reads your existing names.txt file in and displays the contents. It then changes the order by 1 and writes the resulting list back to the same file:

with open('names.txt', 'r') as f:
    list1 = f.read().splitlines()
    print('\n'.join(list1))
    list1 = list1[1:] + list1[:1]

with open('names.txt', 'w') as f:
    f.write('\n'.join(list1))

Run1

Colin
Gary
Gibby
Ross

Run2

Gary
Gibby
Ross
Colin
Martin Evans
  • 45,791
  • 17
  • 81
  • 97