python將輸入文件中的換行符替換為逗號

import os

def replace_newlines_with_commas():
    """
    交互式替換文件中的所有換行符為逗號
    - 提示用戶輸入文件路徑
    - 自動檢測文件是否存在
    - 生成處理后的新文件(原文件名+_processed后綴)
    """
    # 1. 獲取用戶輸入的文件路徑
    while True:
        input_path = input("請輸入需要處理的文件路徑(例如:./名單.txt 或 C:/docs/列表2.txt):").strip()
        # 去除路徑兩端的引號(如果用戶輸入時(shí)帶了引號)
        input_path = input_path.strip('"\'')
        
        # 檢查文件是否存在
        if os.path.exists(input_path):
            break
        else:
            print(f"? 錯誤:文件 '{input_path}' 不存在,請重新輸入!")
    
    # 2. 構(gòu)造輸出文件路徑(原文件同名+_processed)
    file_dir, file_name = os.path.split(input_path)
    file_base, file_ext = os.path.splitext(file_name)
    output_path = os.path.join(file_dir, f"{file_base}_processed{file_ext}")
    
    try:
        # 3. 讀取文件內(nèi)容(兼容UTF-8/GBK編碼,解決中文亂碼問題)
        encodings = ['utf-8', 'gbk', 'gb2312']
        content = None
        for encoding in encodings:
            try:
                with open(input_path, 'r', encoding=encoding) as f:
                    content = f.read()
                print(f"? 成功讀取文件,使用編碼:{encoding}")
                break
            except UnicodeDecodeError:
                continue
        
        if content is None:
            print("? 錯誤:無法識別文件編碼(嘗試了UTF-8/GBK/GB2312)")
            return
        
        # 4. 替換所有換行符(兼容\n、\r\n、\r)
        # 先統(tǒng)一轉(zhuǎn)換為\n,再替換為逗號,避免重復(fù)替換
        content = content.replace('\r\n', '\n').replace('\r', '\n')
        processed_content = content.replace('\n', ',')
        
        # 5. 去除末尾多余的逗號(如果文件最后一行是換行)
        if processed_content.endswith(','):
            processed_content = processed_content[:-1]
        
        # 6. 寫入處理后的內(nèi)容到新文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(processed_content)
        
        # 7. 輸出處理結(jié)果
        print("\n?? 處理完成!")
        print(f"?? 原文件:{input_path}")
        print(f"?? 新文件:{output_path}")
        print(f"?? 替換的換行符數(shù)量:{content.count('\n')}")
        print(f"?? 處理后內(nèi)容預(yù)覽(前150字符):")
        print(processed_content[:150] + "..." if len(processed_content) > 150 else processed_content)
    
    except Exception as e:
        print(f"\n? 處理失?。簕str(e)}")

# 運(yùn)行腳本
if __name__ == "__main__":
    print("=== 換行符替換為逗號工具 ===\n")
    replace_newlines_with_commas()
    input("\n按回車鍵退出...")  # 防止運(yùn)行后窗口直接關(guān)閉
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容