You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从.txt文件随机读取一行并移至另一.txt文件?

嘿,这个需求用Python就能轻松搞定,我给你准备了两种场景的解决方案,对应你文件可能的格式,直接用就行!

解决方案:随机移动文件内容到新文件

首先先确认你的源文件(假设叫source.txt)格式:如果是每行一个条目(比如下面这样),用第一个脚本;如果是所有内容在同一行,用第二个脚本。

每行一个条目的示例:
Michael|30
John|23
Eric|34
Dave|20

单行内容的示例:
Michael|30 John|23 Eric|34 Dave|20

场景1:源文件每行一个条目

完整脚本代码

import random

# 替换成你的实际文件名
source_file = "source.txt"
target_file = "target.txt"

# 读取源文件所有行
with open(source_file, 'r', encoding='utf-8') as f:
    lines = f.readlines()

# 检查源文件是否为空
if not lines:
    print("源文件里没内容,没法移动哦!")
else:
    # 随机选一行的索引
    random_idx = random.randint(0, len(lines)-1)
    selected_line = lines.pop(random_idx)

    # 把剩下的内容写回源文件(实现删除效果)
    with open(source_file, 'w', encoding='utf-8') as f:
        f.writelines(lines)

    # 将选中的行追加到目标文件(不存在会自动创建)
    with open(target_file, 'a', encoding='utf-8') as f:
        f.write(selected_line)

    print(f"搞定!已经把「{selected_line.strip()}」移动到 {target_file} 里啦")

脚本说明

  • 用with open操作文件是最安全的方式,不用手动处理文件关闭的问题。
  • readlines()把文件内容按行存成列表,方便我们随机选择和删除操作。
  • pop()方法既能移除选中的行,又能直接拿到这行内容,一举两得。
  • 目标文件用追加模式('a'),每次移动的内容都会加在末尾,不会覆盖之前的内容。

场景2:源文件所有内容在同一行

如果你的源文件是把所有条目挤在一行的,用这个修改版脚本:

import random

source_file = "source.txt"
target_file = "target.txt"

with open(source_file, 'r', encoding='utf-8') as f:
    content = f.read().strip()

# 按空格拆分条目成列表
items = content.split()
if not items:
    print("源文件是空的!")
else:
    selected_item = random.choice(items)
    items.remove(selected_item)

    # 把剩下的条目拼接成一行写回源文件
    with open(source_file, 'w', encoding='utf-8') as f:
        f.write(' '.join(items))

    # 写入目标文件,加个换行让内容更整齐
    with open(target_file, 'a', encoding='utf-8') as f:
        f.write(selected_item + '\n')

    print(f"搞定!已经把「{selected_item}」移动到 {target_file} 里啦")

小提示

  1. 运行脚本前最好备份一下源文件,避免意外情况丢失数据。
  2. 如果你的文件不在脚本同一个文件夹里,把文件名改成绝对路径就行(比如C:/Users/你的用户名/Documents/source.txt)。
  3. 想要多次移动?重复运行脚本就好,每次都会随机选一个条目移动。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:27:48