我在E:\Desktop\Social_media\edit8\New folder目录中有大量的txt文件,每个文件都有类似如下的排列:

Bolt
2,739,393
Classmates
1,267,092
SixDegrees
1,077,353
PlanetAll
552,488
theGlobe
437,847
OpenDiary
9,251
1998
MARCH
034+

现在我想合并每个txt文件的最后3行,如下所示:

Bolt
2,739,393
Classmates
1,267,092
SixDegrees
1,077,353
PlanetAll
552,488
theGlobe
437,847
OpenDiary
9,251
034+ MARCH 1998

这意味着最后3行必须具有类似number+ month year的排列

I write following python script for this but I don't know why not working:

import os

# Define the directory where your text files are located
directory_path = r'E:\Desktop\Social_media\edit8\New folder'

# Function to rearrange the lines and write to a new file
def rearrange_lines(file_path):
    with open(file_path, 'r') as file:
        lines = [line.strip() for line in file.readlines() if line.strip()]  # Read non-empty lines

    # Check if there are at least 3 non-empty lines
    if len(lines) >= 3:
        lines[-1], lines[-2], lines[-3] = lines[-3], lines[-2], lines[-1]  # Rearrange the last 3 lines

        # Create a new file with the rearranged lines
        with open(file_path, 'w') as file:
            file.write('\n'.join(lines))

# Iterate through each file in the directory
for root, dirs, files in os.walk(directory_path):
    for file_name in files:
        if file_name.endswith('.txt'):
            file_path = os.path.join(root, file_name)
            rearrange_lines(file_path)
            print(f'Rearranged lines in {file_name}')

print('Done!')

Where is my script problem? and how to fix it problem?

推荐答案

您没有在结果中将最后3行合并为一行.

# Function to rearrange the lines and write to a new file
def rearrange_lines(file_path):
    with open(file_path, 'r') as file:
        lines = [line.strip() for line in file.readlines() if line.strip()]  # Read non-empty lines

    # Check if there are at least 3 non-empty lines
    if len(lines) >= 3:
        # reverse last 3 lines, join them with space, and replace with this result
        lines[-3:] = [' '.join(lines[-1:-4:-1])]

        # Create a new file with the rearranged lines
        with open(file_path, 'w') as file:
            file.write('\n'.join(lines))

将值指定给lines[-3:]是切片替换.我们将其替换为一行的列表.

Python相关问答推荐

Flask:如何在完整路由代码执行之前返回验证

合并同名列,但一列为空,另一列包含值

Polars Dataframe:如何按组删除交替行?

如果我已经使用了time,如何要求Python在12秒后执行另一个操作.sleep

如何修复使用turtle和tkinter制作的绘画应用程序的撤销功能

查找下一个值=实际值加上使用极点的50%

使用Ubuntu、Python和Weasyprint的Docker文件-venv的问题

在matplotlib动画gif中更改配色方案

max_of_three使用First_select、second_select、

Pytest两个具有无限循环和await命令的Deliverc函数

Python中的嵌套Ruby哈希

将两只Pandas rame乘以指数

无法通过python-jira访问jira工作日志(log)中的 comments

为一个组的每个子组绘制,

在两极中过滤

如果初始groupby找不到满足掩码条件的第一行,我如何更改groupby列,以找到它?

python—telegraph—bot send_voice发送空文件

python sklearn ValueError:使用序列设置数组元素

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

语法错误:文档. evaluate:表达式不是合法表达式