How to sort a text file line-by-line
fn = 'filename.txt'
sorted_fn = 'sorted_filename.txt'
with open(fn,'r') as first_file:
rows = first_file.readlines()
sorted_rows = sorted(rows, key=lambda x: int(x.split()[0]), reverse=False)
with open(sorted_fn,'w') as second_file:
for row in sorted_rows:
second_file.write(row)
This should work for a text file of 3+ million rows. Using int(x.split()[0])
will sort the first item in each row as an integer
Edited to remove close() statements
How to sort out a text file in python using numbers in the text file
Using python and no system calls:
# This is the function to amend when you want to change the ordering
def key_function(line):
# To sort by the first number when there is a space
return int(line.split()[0])
To extract any number that begins the line you can use a regex
def key_function(line):
match = re.match('^\d+', line)
if match:
return int(match.group())
else:
return 0
Then the rest of the method is the same
with open(file_name, 'r') as f:
# Read all lines into a list
lines = f.readlines()
with open(file_name, 'w') as f:
# Sort all the lines by "key_function"
for line in sorted(lines, key=key_function, reverse=True):
f.write(line + '\n')
How can I sort numbers in text file from smallest to largest?
This will print out the 5 smallest numbers
f = open("highscore.txt", "r+")
numbers = sorted(list(map(int, f.readlines())))
print(numbers[:5])
Arrange a Text file using python
You are trying to transform lines of text to columns. This code is supposing that in your file blah.txt
you are having same amount of headers and values:
with open('blah.txt', 'r') as f_in, open('out.txt','w',newline='') as f_out:
lines = [l.strip() for l in f_in.readlines()]
headers, values = lines[:len(lines)//2], lines[len(lines)//2:]
for h in headers:
f_out.write(h + '\t\t')
f_out.write('\n')
for v in values:
f_out.write(v + '\t\t')
f_out.write('\n')
With this the out.txt will be:
serial name phone gmail
1 blah blah 55555 blah@blah.com
How to sort lines in a text file by last name in python?
The logic is straight forward for this.
- Read each line into a dictionary with the last name as the key
- Sort the keys
- Output the lines based on key (last name)
Try this code:
ss = '''
(fname3) (lname8) (12) (NY)
(fname2) (lname7) (34) (PA)
(fname4) (lname9) (11) (SF)
(fname1) (lname4) (40) (LA)
(fname5) (lname5) (5) (LV)
'''.strip()
with open ('names.txt','w') as f: f.write(ss) # write data file
#########################
with open('names.txt') as f:
lines = f.readlines()
d = {ln.split()[1]:ln.strip() for ln in lines} # use last name (col 2) as key
keysort = sorted([k for k in d]) # sort keys
for k in keysort:
print(d[k])
Output
(fname1) (lname4) (40) (LA)
(fname5) (lname5) (5) (LV)
(fname2) (lname7) (34) (PA)
(fname3) (lname8) (12) (NY)
(fname4) (lname9) (11) (SF)
Note that you can also split all the lines into arrays then sort the lines based on array index. The csv module can help with this.
Open a text file,sort the text file and then save it using Python
You can use this with f.write()
:
with open('sort.txt', 'r') as f:
lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()
with open('sorted.txt', 'w') as f: # open sorted.txt for writing 'w'
# join numbers with newline '\n' then write them on 'sorted.txt'
f.write('\n'.join(str(n) for n in numbers))
Input (sort.txt
):
1
-5
46
11
133
-54
8
0
13
10
Output (sorted.txt
):
-54
-5
0
1
8
10
11
13
46
133
How do I arrange the lines of a txt file with numbers?
As @mkrieger1 said, You should enumerate wordlist, not line:
for count, ele in enumerate(wordlist, 1):
print([count, ele])
Example:
wordlist = ['balboa','bbbbb1','banks','badabing','harriet']
Output:
[1, 'balboa']
[2, 'bbbbb1']
[3, 'banks']
[4, 'badabing']
[5, 'harriet']
Related Topics
Conda: Remove All Installed Packages from Base/Root Environment
Subtracting Values Across Grouped Data Frames in Pandas
How to Automatically Download Files from a Pop Up Dialog Using Selenium-Python
How to Install Colorama in Python
Opencv - Saving Images to a Particular Folder of Choice
How to Scroll a Web Page Using Selenium Webdriver in Python
How to Split a Huge Text File in Python
Replacing Special Characters in a List in Python
How to Remove Lowest Elements in List
Cannot Find Reference 'Xxx' in _Init_.Py
Removing Non-Breaking Spaces from Strings Using Python
Shifting the Elements of an Array in Python
How to Remove Carriage Return in a Dataframe
Permissionerror: [Errno 13] Permission Denied
Import a File from a Subdirectory
Typeerror: Unsupported Operand Type(S) for ** or Pow(): 'List' and 'Int'