Home > database >  Swap the word and the numbers from a file and write a new file
Swap the word and the numbers from a file and write a new file

Time:01-23

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

CodePudding user response:

  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

CodePudding user response:

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
  • Related