gpt4 book ai didi

python - 在 Python 中将行从一个 CSV 附加到另一个

转载 作者:行者123 更新时间:2023-12-04 12:43:40 25 4
gpt4 key购买 nike

我已经为此查看了许多解决方案,但找不到适合我想做的事情的解决方案。

基本上我有2个CSV文件:

all.csv


1   Wed Oct 03  41.51093923 41.51093923 41.51093923 41.51093923         
2 Wed Oct 04
3 Wed Oct 05 41.43764015 41.43764015 41.43764015
4 Wed Oct 06 41.21395681 41.21395681 41.21395681
5 Wed Oct 07 42.07607442 42.07607442 42.07607442
6 Wed Oct 08 42.0074109 42.0074109 42.0074109
7 Wed Oct 09 41.21395681 41.21395681
8 Wed Oct 10 41.43764015 41.43764015 41.43764015 41.43764015
9 Wed Oct 11 41.21395681 41.21395681 41.21395681 41.21395681

original.csv


10  Wed Oct 12  41.43764015             
11 Wed Oct 13
12 Wed Oct 14 42.07607442 42.07607442 42.07607442
13 Wed Oct 15 41.43764015 41.43764015 41.43764015 41.43764015
14 Wed Oct 16 41.21395681 41.21395681 41.21395681 41.21395681
15 Wed Oct 17
16 Wed Oct 18 42.07607442 42.07607442 42.07607442

我想追加 original.csvall.csv ,通过简单地获取 original.csv 中的所有行并将它们合并到 all.csv 中的最后一行之下要得到:
1   Wed Oct 03  41.51093923 41.51093923 41.51093923 41.51093923         
2 Wed Oct 04
3 Wed Oct 05 41.43764015 41.43764015 41.43764015
4 Wed Oct 06 41.21395681 41.21395681 41.21395681
5 Wed Oct 07 42.07607442 42.07607442 42.07607442
6 Wed Oct 08 42.0074109 42.0074109 42.0074109
7 Wed Oct 09 41.21395681 41.21395681
8 Wed Oct 10 41.43764015 41.43764015 41.43764015 41.43764015
9 Wed Oct 11 41.21395681 41.21395681 41.21395681 41.21395681
10 Wed Oct 12 41.43764015
11 Wed Oct 13
12 Wed Oct 14 42.07607442 42.07607442 42.07607442
13 Wed Oct 15 41.43764015 41.43764015 41.43764015 41.43764015
14 Wed Oct 16 41.21395681 41.21395681 41.21395681 41.21395681
15 Wed Oct 17
16 Wed Oct 18 42.07607442 42.07607442 42.07607442

如您所见,数据没有标题,行的长度各不相同。这只是我正在使用的文件类型的一个示例,但我想获得一个可以处理任何 CSV 的解决方案。

我正在使用 Python3,到目前为止已经尝试使用 pandas图书馆,但没有运气。

任何建议都会很棒,谢谢。

最佳答案

您不需要使用 pandas .只需将一个 csv 附加到另一个:

with open('original.csv', 'r') as f1:
original = f1.read()

with open('all.csv', 'a') as f2:
f2.write('\n')
f2.write(original)

输出:
1   Wed Oct 03  41.51093923 41.51093923 41.51093923 41.51093923
2 Wed Oct 04
3 Wed Oct 05 41.43764015 41.43764015 41.43764015
4 Wed Oct 06 41.21395681 41.21395681 41.21395681
5 Wed Oct 07 42.07607442 42.07607442 42.07607442
6 Wed Oct 08 42.0074109 42.0074109 42.0074109
7 Wed Oct 09 41.21395681 41.21395681
8 Wed Oct 10 41.43764015 41.43764015 41.43764015 41.43764015
9 Wed Oct 11 41.21395681 41.21395681 41.21395681 41.21395681
10 Wed Oct 12 41.43764015
11 Wed Oct 13
12 Wed Oct 14 42.07607442 42.07607442 42.07607442
13 Wed Oct 15 41.43764015 41.43764015 41.43764015 41.43764015
14 Wed Oct 16 41.21395681 41.21395681 41.21395681 41.21395681
15 Wed Oct 17
16 Wed Oct 18 42.07607442 42.07607442 42.07607442

关于python - 在 Python 中将行从一个 CSV 附加到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54749793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com