简体   繁体   中英

How can I transform each 7 row to single row in csv file with python?

csv file example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

new csv file which I want:

1    2    3    4    5    6    7
8    9    10   11   12   13   14
15   16   17   18   19   20   21

Note: I want tab between each numbers.

This can be done in pandas :

import pandas as pd
df = pd.read_csv('filename.csv', header=None)
df = pd.DataFrame(df.values.reshape(-1, 7))
df.to_csv("output.csv", sep="\t", header=False)

output df :

0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
1 8 9 10 11 12 13 14
2 15 16 17 18 19 20 21
file = open("yourFile.csv", "r") newFile = open("newFile.csv", "w") for line in file.read().strip().split("\n"): newFile.write(line) if (int(line) % 7 == 0): newFile.write("\n") else: newFile.write("\t") file.close() newFile.close()

I would have preferred that you show your work first before I post the answer.

Here's the answer anyway so it gives you some pointers to solve this.

with open('abc.txt', 'r') as f1, open ('xyz.txt','w') as f2:
    write_line = ''
    for i, line in enumerate(f1):
        line = line.strip()
        if i != 0 and i %7 == 0:
            write_line += '\n'
            f2.write(write_line)
            write_line = line + '\t'
        else:
            write_line += line + '\t'
    if i != 0 and i %7 != 0:
        f2.write(write_line)

Keep track of the row you read. If the row is the first one (i==0), just add the line + \t to a temp variable. If the line is the 8th / 15th /... (i%7 ==0), then you have read 7 rows already. So write the data into the output file. Then reset the temp variable so you can do this again.

Once you are out of the loop, you want to make sure you write the last set of rows. Sometimes the file may end up having 20 rows. So you want to ensure you write the last 6 rows into the output file.

The output of this will be:

1   2   3   4   5   6   7   
8   9   10  11  12  13  14  
15  16  17  18  19  20  21  

If the input file had values from 1 thru 24, the output file would look like this:

1   2   3   4   5   6   7   
8   9   10  11  12  13  14  
15  16  17  18  19  20  21  
22  23  24  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM