Transposing a text file in Python

后端 未结 3 1284
梦谈多话
梦谈多话 2021-01-21 12:17

I have a text file that I would like to transpose using Python.

For example, given the following file:

asdfg
qwert

I would like the out

相关标签:
3条回答
  • 2021-01-21 13:19

    Maybe this is you wanted:

    with open("/Users/wy/Desktop/wy.txt", "r") as cin:
        lines = cin.read()
    lineStr = lines.split('\n')
    
    with open("/Users/wy/Desktop/res.txt", "w") as cout:
        for ele in zip(*lineStr):
            cout.write(''.join(list(ele)) + '\n')
    
    0 讨论(0)
  • 2021-01-21 13:21

    Make use of readlines() to get a list for each line.

    And for a clean approach, try zip:

    a = "asdfg"
    b = "qwert"
    
    print zip(a, b)
    

    Gives:

    [('a', 'q'), ('s', 'w'), ('d', 'e'), ('f', 'r'), ('g', 't')]
    

    From there, iterate over each element and print out the results.

    0 讨论(0)
  • 2021-01-21 13:24

    Setup

    First lets set up our file for those of us who haven't set it up, but you can skip to the read part below, just ensure you change the filepath variable to reflect the location and name of your file:

    import textwrap
    
                  # dedent removes the extra whitespace in front of each line
    text = textwrap.dedent("""
        asdfg
        qwert""").strip() # strip takes off the first newline
    
    filepath = '/temp/foo.txt'
    
    with open(filepath, 'w') as writer:
        writer.write(text)
    

    Read the file

    So now we have our file in place, let's read it back in to the text variable, using the with context manager (so if we have an error, it automatically closes the file for us, and we can easily recover.):

    with open(filepath, 'rU') as reader:
        text = reader.read()
    

    Manipulate the text

    And here's the magic, split the lines of the text so that we have a list of two strings, expand that list into two arguments (with the *) passed to zip, which then goes through the strings by character pairwise, joining the pairs with an empty string, and then we print each member of that list:

    list_of_strings = [''.join(chars) for chars in zip(*text.splitlines())]
    
    for string_i in list_of_strings:
        print(string_i)
    

    should print

    aq
    sw
    de
    fr
    gt
    
    0 讨论(0)
提交回复
热议问题