簡體   English   中英

使用 Python 重命名(更改)文件名並刪除數據(特定字符)

[英]Rename(change) file name and remove data (specific characters) using Python

我編寫了如何在 python 中使用 pandas 加載和保存 txt 文件的代碼。


import glob

filenames = sorted(glob.glob("D:/a/test*.txt"))
filenames = filenames[0:5]

import numpy as np
import pandas as pd

for f in filenames:
  df = pd.read_csv(f, skiprows=[1,2,3], dtype=str, delim_whitespace=True) 
  df.to_csv(f'{f[:-4]}.csv', index=False)

 ------>There are 10 result files in a folder 
 - test1.txt, test2.txt, test3.txt, test4.txt, test5.txt, 
 test1.csv, test2.csv, test3.csv, test4.csv, test5.csv

#Result csv.file(test1.csv)

abc:,1.233e-03
1.234e-04,
1.235e-02,
1.236e-05,
1.237e-02,
1.238e-02,

但我有一些問題如下。

  1. I don't know how to rename test1.txt, test2.txt, test3.txt, test4.txt, test5.txt into c1.csv, c2.csv, c3.csv, c4.csv, c5.csv.

  2. 我想刪除所有 test(1,2,3,4,5).csv 文件中的 'abc:,' 數據,但我不知道如何刪除和替換數據。

你知道如何重命名(更改)文件名和刪除python中提到的上述問題的數據(特定字符)嗎?

origin data
test1.txt (it is similar to other file-{test2,test3,test4, test5}.txt)
abc:  1.233e-03
def:  1.64305155216978164e+02
ghi: 4831
jkl:
 1.234e-04
 1.235e-02
 1.236e-05
 1.237e-02
 1.238e-02

Expected result
(it must chage test1,2,3,4,5.txt files into c1,2,3,4,5.csv files, it only remove herder name(abc:), also def:,ghi:,jkl: rows should remove.)
 1.233e-03
 1.234e-04
 1.235e-02
 1.236e-05
 1.237e-02
 1.238e-02

這是您可以執行的操作:

import os
import glob
import pandas as pd


for f in glob.glob("*.txt"):
    df = pd.read_csv(f, skiprows=[1,2,3], dtype=str, delim_whitespace=True)
    df = df.replace('abc:,','')
    os.rename(f,f'{f[:-4]}.csv')
    df.to_csv(f'{f[:-4]}.csv', index=False)
  1. 您可以使用os.rename()方法重命名文件,也可以使用f= open("file_name.extension","w+")創建一個新文件並將 output 寫入新文件。

  2. 一旦將數據加載到字符串變量中,就可以使用replace()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM