You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Python实现读取TXT文件并在指定索引位置后添加空格

Fixing Your Python TXT Line Editing Code

Got it, let's get this sorted for you. The issue with your current code is that it's just duplicating the entire line with a space in between—totally not what you need for inserting spaces at specific index positions.

First, let's clarify a key trick here: when inserting spaces into a string, if we do it from right to left (starting with the largest index first), we don't have to worry about inserted spaces shifting the positions of the remaining indices we need to handle. That's because adding a space to the end of the string doesn't affect the indices of characters before it.

Here's the Corrected Code

# Define the indices where we need to add a space AFTER the index (0-based)
insert_indices = [2, 6, 11, 21]
# Sort indices in descending order to avoid shifting issues
insert_indices_sorted = sorted(insert_indices, reverse=True)

# Read the file content
with open("C:/path-to-file/file.txt", "r") as file:
    lines = file.read().split("\n")

new_lines = []
for line in lines:
    # Skip empty lines if needed (adjust based on your file's structure)
    if not line.strip():
        new_lines.append(line)
        continue
    
    modified_line = line.rstrip()
    for idx in insert_indices_sorted:
        # Ensure we don't try to insert beyond the line's length
        if idx < len(modified_line):
            # Insert space right after the specified index
            modified_line = modified_line[:idx+1] + ' ' + modified_line[idx+1:]
    new_lines.append(modified_line)

# Write the modified content back to the file
with open("C:/path-to-file/file.txt", "w") as newfile:
    newfile.write("\n".join(new_lines))

Let's Break Down What This Does

  • Sorted Indices: By sorting insert_indices in reverse order, we start inserting spaces from the end of the line first. This way, inserting a space doesn't change the position of the indices we haven't processed yet (since they're to the left of the current insertion point).
  • Line Processing: For each line, we loop through our sorted indices. For each valid index (that's within the line's length), we split the string right after the target index, insert a space, and rejoin the parts.
  • Error Prevention: The check if idx < len(modified_line) ensures we don't try to insert a space beyond the end of the line, which would cause an index error.

Example Test

If your original line is:

12345 678 91011 12 1314

Running this code will turn it into:

123 45 6 78 91 011 12 131 4

Which matches exactly what you're looking for!

内容的提问来源于stack exchange,提问作者bashar

火山引擎 最新活动