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
awk
command would be a much cleaner solution. awk '{print $2, $1}' < oldfile > newfile
f
for readingg
for writingf
:
a
and b
b
and a
in swapped order with a space in betweeng
f
and g
with
, and if you're not using with
, you're probably doing it wrong. with
to ensure closing files is preferred. You can do this in 3 clean steps with a pandas dataframe.
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