在Python中拆分原始数据

发布于 2025-02-08 12:36:28 字数 401 浏览 0 评论 0原文

我想从Python删除TXT文件的原始数据。这样的原始数据:

-0.156 200

-0.157 300

-0.158 400

-0.156 201

-0.157 305

-0.158 403

-0.156 199

-0.157 308

-0.158 401

我希望将文件提取到这样的许多TXT文件。

-0.156 200

-0.157 300

-0.158 400

-0.156 201

-0.157 305

-0.158 403

-0.156 199

-0.157 308

-0.158 401

你能帮我吗?

I want to cut the raw data from txt file by python. The raw data like this:

-0.156 200

-0.157 300

-0.158 400

-0.156 201

-0.157 305

-0.158 403

-0.156 199

-0.157 308

-0.158 401

I expect to extract the file to many txt file like this.

-0.156 200

-0.157 300

-0.158 400

-0.156 201

-0.157 305

-0.158 403

-0.156 199

-0.157 308

-0.158 401

Would you please help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕花眠 2025-02-15 12:36:28

这将数据分配给每个文件中的三个条目

READ_FROM = 'my_file.txt'

ENTRIES_PER_FILE = 3

with open(READ_FROM) as f:
    data = f.read().splitlines()
    i = 1
    n = 1
    for line in data:
        with open(f'new_file_{n}.txt', 'a') as g:
            g.write(line + '\n')
            i += 1
        if i > ENTRIES_PER_FILE:
            i = 1
            n += 1

new_file_1.txt

-0.156 200
-0.157 300
-0.158 400

new_file_2.txt

-0.156 201
-0.157 305
-0.158 403

new_file_3.txt中的三个条目

-0.156 199
-0.157 308
-0.158 401

This splits the data into files with three entries in each file

READ_FROM = 'my_file.txt'

ENTRIES_PER_FILE = 3

with open(READ_FROM) as f:
    data = f.read().splitlines()
    i = 1
    n = 1
    for line in data:
        with open(f'new_file_{n}.txt', 'a') as g:
            g.write(line + '\n')
            i += 1
        if i > ENTRIES_PER_FILE:
            i = 1
            n += 1

new_file_1.txt

-0.156 200
-0.157 300
-0.158 400

new_file_2.txt

-0.156 201
-0.157 305
-0.158 403

new_file_3.txt

-0.156 199
-0.157 308
-0.158 401
意犹 2025-02-15 12:36:28

如果线之间有空格,并且希望在新文件中的行之间的线路之间有空间,这将有效:

with open('path/to/file.txt', 'r') as file:
    lines = file.readlines()
cleaned_lines = [line.strip() for line in lines if len(line.strip()) > 0]
num_lines_per_file = 3
for num in range(0, len(cleaned_lines), num_lines_per_file):
    with open(f'{num}.txt', 'w') as out_file:
        for line in cleaned_lines[num:num + num_lines_per_file]:
            out_file.write(f'{line}\n\n')

If you have spaces between your lines and you want spaces between your lines in your new file this will work:

with open('path/to/file.txt', 'r') as file:
    lines = file.readlines()
cleaned_lines = [line.strip() for line in lines if len(line.strip()) > 0]
num_lines_per_file = 3
for num in range(0, len(cleaned_lines), num_lines_per_file):
    with open(f'{num}.txt', 'w') as out_file:
        for line in cleaned_lines[num:num + num_lines_per_file]:
            out_file.write(f'{line}\n\n')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文