Questions & Answers

Swap the word and the numbers from a file and write a new file

How do I swap two items in a file which contains words on the left and numbers on the right?

I want to achieve numbers on the right and strings on the left.

I have a text file that contains huge numbers i.e corpus:

200 Apple
200 Banana
1 Hi
1 Hello
1112 Elevator
2023-01-23 00:30:07
If this format is consistent, and if you're on a unix platform, then I think the awk command would be a much cleaner solution. awk '{print $2, $1}' < oldfile > newfile
2023-01-23 00:30:07
Is there always only ever one blank space on each line? If so, read it into pandas as a csv file (but specify space as the separator, and no header), then swap the columns and write it back out again.
Answers(2) :
  1. open file f for reading
  2. open file g for writing
  3. loop over all lines in file f:
    • split the line at the first space into parts a and b
    • concatenate parts b and a in swapped order with a space in between
    • write concatenated line to file g
  4. close files f and g
2023-01-23 00:30:07
If you have to close files, you're not using with, and if you're not using with, you're probably doing it wrong.
2023-01-23 00:30:07
That's true. Using with to ensure closing files is preferred.

You can do this in 3 clean steps with a pandas dataframe.

  1. read file
  2. swap columns
  3. write new file

so the code looks like this:

import pandas as pd

# read into dataframe
data = pd.read_csv("some_file.txt", delimiter=" ", header=None)

# swap columns
data[0], data[1] = data[1], data[0]

# write data to a new file
data.to_csv("some_file_new.txt", header=False, index=False, sep = ' ')

print('file written !!')

and the new file contents looks like this:

Apple 200
Banana 200
Hi 1
Hello 1
Elevator 1112