Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python 3.x - How can I merge two files with numbers into a new file and make it sorted?

How can I merge two files with numbers into a new file and make it sorted?

Code:

#combining the two files
filenames = ["numbers1.txt", "numbers2.txt"]
    with open("allNumbers.txt", "w") as al_no:
       **#iterating through the filenames list**
        for f in filenames:
           with open(f) as infile:
                for line in infile:
                    al_no.write(line)
question from:https://stackoverflow.com/questions/65650740/how-can-i-merge-two-files-with-numbers-into-a-new-file-and-make-it-sorted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two approaches you can use.

The first approach is to loop through, append the lines to a list, sort the list and then write that out to the file.

filenames = ["numbers1.txt", "numbers2.txt"]

# Step 1: merge the lines into a list
lines = []
for f in filenames:
   with open(f) as infile:
        for line in infile:
            lines.append(line)

# Step 2: write the list out to the file in a sorted order
with open("allNumbers.txt", "w") as all_no:
    all_no.write(''.join(sorted(lines, key=lambda x: int(x.strip()))))

It is more succinct (and Pythonic) to use list comprehensions instead:

filenames = ["numbers1.txt", "numbers2.txt"]

lines = [line for sublist in [open(f).readlines() for f in filenames] for line in sublist]
with open("allNumbers.txt", "w") as all_no:
    all_no.write(''.join(sorted(lines, key=lambda x: int(x.strip()))))

Remember that when sorting, you need to use the key argument to sorted to ensure a numeric sort is done, rather than the default lexicographic sort.

This code assumes that each line in the source files contains a number, which is likely given the current approach you've taken.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...