-3

i have 2 text files.

file1:

Good morning .
How are you today ?

and file2:

1 0 .
1 0 2 0 .

How can we make one text file like below:

Good/1 morning/0 ./.
How/1 are/0 you/2 today/0 ?/.

Any help?

  • 2
    by actually reading file and do what you want, where did you exactly stock? – ᴀʀᴍᴀɴ Dec 20 '18 at 08:20
  • 1
    `zip` will allow you to iterate over two lists simultaneously `join` is a string method that you can use to put the elements you need together. Take a look at the Python docs on reading files. https://docs.python.org/3/tutorial/inputoutput.html – Andrew Dec 20 '18 at 08:25
  • Hello and welcome to SO. You're question as currently formulated is way too broad, please post what you're tried that didn't work. – bruno desthuilliers Dec 20 '18 at 09:00

3 Answers3

3

You can split a line into a list of words based upon spaces as a breaking character:

>>> line1 = 'Good morning .'
>>> line1.split()
['Good', 'morning', '.']

You can zip lists together to get pairings of first, second, third elements of each list:

>>> line2 = '1 0 .'
>>> zipped = list(zip(line1.split(), line2.split()))
>>> zipped
[('Good', '1'), ('morning', '0'), ('.', '.')]

We can then format each pair into a new string:

>>> '{}/{}'.format(*('Good', '1'))
'Good/1'

We use str.join for each pair in the sequence.

Putting it all together:

with open('output', 'w') as output:
     with open('file1') as file1:
         with open('file2') as file2:
             for line1, line2 in zip(file1, file2):
                 output_line = ' '.join('{}/{}'.format(*pair)
                                        for pair in zip(line1.split(), line2.split()))
                 output.write(output_line + '\n')

edit: also we could join each pair into a new string, which is terser:

>>> pair = ('Good', '1')
>>> '/'.join(pair)
'Good/1'

So, you would instead get:

output_line = ' '.join('/'.join(pair)
                       for pair in zip(line1.split(), line2.split()))

Note, I also added a missing \n character when writing to the output file.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
2

You could just read both files, format the content and then write out your content on a new file

# Read out the file contents
def read_file(file_path):
    lines = []
    with open(file_path, 'r') as file:
        lines = [line.strip().split() for line in file]
    return lines

# Merge the contents of two files
def merge_files(file1_path, file2_path, output_path='output.txt'):
    # Read and store the contents of both files
    file_1 = read_file(file1_path)
    file_2 = read_file(file2_path)

    # Create the output/merged file
    with open(output_path, 'w') as output_file:
        # Iterate over the first files content
        for row_idx in range(len(file_1)):

            file_1_row = file_1[row_idx]
            file_2_row = file_2[row_idx]

            # Merge the matching row of each file
            content_row = [
                "{}/{}".format(file_1_row[word_idx], file_2_row[word_idx])
                for word_idx in range(len(file_1_row))
            ]
            # Write the merged row into the new file
            output_file.write(" ".join(content_row))
            output_file.write("\n")

if __name__ == "__main__":
    merge_files('file1.txt', 'file2.txt')
    # If you need the output file in a different file
    # merge_files('file1.txt', 'file2.txt', output_path='output.txt')

This will generate your merged file into output.txt by default. This also assumes that your data is correct where the file rows match the expected count.

fixatd
  • 1,394
  • 1
  • 11
  • 19
0

You can read the file and store the values into list. Then you can do whatever you want by accesing the list element via index.

You can check this Concatenate text files and for reading the file read a file line-by-line into a list

Aybars
  • 395
  • 2
  • 11