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:
- open file
f
for reading - open file
g
for writing - loop over all lines in file
f
:- split the line at the first space into parts
a
andb
- concatenate parts
b
anda
in swapped order with a space in between - write concatenated line to file
g
- split the line at the first space into parts
- close files
f
andg
CodePudding user response:
You can do this in 3 clean steps with a pandas dataframe.
- read file
- swap columns
- 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