简体   繁体   English

Python,如何创建仅包含以特定短语开头的特定行的文件

[英]Python, how to create file containing only specific lines beginning with certain phrase

I have certain lines of data within a large file that the only lines I need are the ones that begin with "ABC".我在一个大文件中有某些数据行,我需要的唯一行是以“ABC”开头的行。 I wasn't sure if there was a way to pull all these lines and create a new folder to contain only the xyz coordinates within it, as I need to find the standard deviation and think that would be the best way to go about It.我不确定是否有办法拉出所有这些线并创建一个新文件夹以仅包含其中的 xyz 坐标,因为我需要找到标准偏差并认为这将是解决它的最佳方法。 (An example line of the overall file that's being worked with: "ABC 3.2650481094164707 5.5229511970397915 4.8978200015718540") (正在使用的整个文件的示例行:“ABC 3.2650481094164707 5.5229511970397915 4.8978200015718540”)

Ideally it would be a file with column format so that the example coordinates are as such: "3.2650481094164707, 5.5229511970397915, 4.8978200015718540" so that there is an x column, ay column and az column理想情况下,它将是一个列格式的文件,以便示例坐标如下:“3.2650481094164707、5.5229511970397915、4.8978200015718540”,这样就有一个 x 列、ay 列和 az 列

The following is the format of the code to obtain just the ABC lines, but I'm unsure how to make them into their own file以下是仅获取ABC行的代码格式,但我不确定如何将它们制作成自己的文件

with open("file",'r') as f:
    sums = [0] * 3
    points = 0
    for line in f:
        if line.startswith("ABC "):
            points += 1
            for i, x in enumerate(line.split()[1:]):
                sums[i] += float(x)

To get lines from the input file which starts with ABC and write it to CSV file you can use next example:要从以ABC开头的输入文件中获取行并将其写入 CSV 文件,您可以使用下一个示例:

import csv

abc_lines = []
with open("your_file.txt", "r") as f_in:
    for line in map(str.strip, f_in):
        if not line.startswith("ABC "):
            continue
        abc_lines.append(line.split()[1:])


with open("data.csv", "w") as f_out:
    writer = csv.writer(f_out)

    writer.writerow(["X", "Y", "Z"])
    writer.writerows(abc_lines)

Creates data.csv :创建data.csv

X,Y,Z
3.2650481094164707,5.5229511970397915,4.8978200015718540
4.2650481094164707,6.5229511970397915,7.8978200015718540

Input file:输入文件:

ABC 3.2650481094164707 5.5229511970397915 4.8978200015718540
XYZ 3.2650481094164707 5.5229511970397915 4.8978200015718540
ABC 4.2650481094164707 6.5229511970397915 7.8978200015718540

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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