import os
# 第一步:打开文件,将文件中一个或多个连续的空格替换成一个空格
# 打开要修改的txt文件
f = open("12345.txt", "r", encoding="utf-8")
for line in f.readlines():
# 输入到一个新的文件中
with open("xu_1.txt", "a", encoding="utf-8") as m:
m.write(" ".join(line.split()).join("\r\n"))
# 第二步:将刚才修改替换好的文件中的空格替换成tab,方便excel处理
# 读取的文件目录和文件名
read_file_path = "xu_1.txt"
# 写入的文件目录和文件名
write_file_path = "xu_2.txt"
# 使用os.path.join()拼接路径
read_file_path = os.path.join(os.getcwd(), read_file_path)
write_file_path = os.path.join(os.getcwd(), write_file_path)
with open(read_file_path, "r", encoding="utf-8") as f:
for line in f.readlines():
# 使用with open() as自动处理文件的打开和关闭
with open(write_file_path, "a", encoding="utf-8") as m:
# 使用str.replace()将所有的空格替换为制表符
m.write(line.replace(" ", "\t"))
# 第三步:删除文件中的空行(如果有的话)
# 打开输入文件和输出文件
with open("xu_2.txt", "r", encoding="utf-8") as input_file, open(
"xu_3.txt", "w", encoding="utf-8"
) as output_file:
# 遍历输入文件的每一行
for line in input_file:
# 如果行不为空,则写入到输出文件
if line.strip():
output_file.write(line)
# 提示用户已完成删除空行的操作
print("空行已删除,结果保存在output.txt文件中。")
# 第四步:如果标签是中文,则给它添加上英文双引号
# 打开输入文件和输出文件
with open("123.txt", "r", encoding="utf-8") as input_file, open(
"xu_4.txt", "w", encoding="utf-8"
) as output_file:
# 遍历输入文件的每一行
for line in input_file:
# 分割行中的字段
fields = line.strip().split()
# 对汉字部分添加英文双引号
modified_fields = [
'"{}"'.format(field) if field.isalpha() else field for field in fields
]
# 拼接修改后的行并写入输出文件
output_file.write(" ".join(modified_fields) + "\n")
# 提示用户已完成修改操作
print("文件已成功修改。")
# 第五步:将刚才修改替换好的文件中的空格替换成tab,方便excel处理
# 读取的文件目录和文件名
read_file_path = "xu_4.txt"
# 写入的文件目录和文件名
write_file_path = "xu_5.txt"
# 使用os.path.join()拼接路径
read_file_path = os.path.join(os.getcwd(), read_file_path)
write_file_path = os.path.join(os.getcwd(), write_file_path)
with open(read_file_path, "r",encoding="utf-8") as f:
for line in f.readlines():
# 使用with open() as自动处理文件的打开和关闭
with open(write_file_path, "a",encoding="utf-8") as m:
# 使用str.replace()将所有的空格替换为制表符
m.write(line.replace(" ", "\t"))
# 第六步:删除文件中的空行(如果有的话)
# 打开输入文件和输出文件
with open("xu_5.txt", "r", encoding="utf-8") as input_file, open(
"000.txt", "w", encoding="utf-8"
) as output_file:
# 遍历输入文件的每一行
for line in input_file:
# 如果行不为空,则写入到输出文件
if line.strip():
output_file.write(line)
# 提示用户已完成删除空行的操作
print("空行已删除,结果保存在output.txt文件中。")
本文章使用limfx的vscode插件快速发布