我對 Python 完全陌生,因為我有一項要完成的特定任務。我有一個很大的 .XY 檔案資料集(基本上是 .txt 檔案),每個檔案都有 23 行的標題。我希望使用 Python(Python 3.7,通過 Visual Studio 代碼)從與原始檔案格式相同的所有檔案中洗掉標題(從原始檔案中洗掉,或寫入新檔案)。我希望編輯的檔案頂部的示例如下所示:
# Distance Sample to Detector: 0.3004918066158592 m
# PONI: 1.261e-01, 1.147e-01 m
# Rotations: 0.000061 0.000011 -0.000000 rad
#
# == Fit2d calibration ==
# Distance Sample-beamCenter: 300.492 mm
# Center: x=1529.147, y=1680.772 pix
# Tilt: 0.004 deg TiltPlanRot: 169.652 deg
#
# Detector Detector Spline= None PixelSize= 7.500e-05, 7.500e-05 m
# Detector has a mask: False
# Detector has a dark current: False
# detector has a flat field: False
#
# Wavelength: 4.1069000000000004e-11 m
# Mask applied: None
# Dark current applied: None
# Flat field applied: None
# Polarization factor: None
# Normalization factor: None
#
# 2th_deg I
1.441032378E 00 -3.563451171E-01
1.447230367E 00 1.410741210E-01
1.453428356E 00 6.531007886E-01
1.459626345E 00 1.176007986E 00
1.465824333E 00 1.784591913E 00
uj5u.com熱心網友回復:
打開檔案,讀入,然后只使用您需要的行。
使用
使用 with 將打開檔案,然后在塊完成后它會自動關閉檔案物件。
with open('filename.txt', 'r') as input_file:
lines = input_file.readlines()
input_you_need = lines[23:]
#do something with input_you_need
使用打開和關閉
使用 open 將為腳本的其余部分打開檔案,或者直到您關閉它。始終關閉您的檔案
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
lines_needed = Lines[23:]
file1.close()
# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(lines_needed)
file1.close()
uj5u.com熱心網友回復:
您的程式需要經過以下步驟:
- 遍歷資料集中的所有檔案
- 讀入每個檔案的內容并
- 僅將所需的行寫入新檔案。
第一步,該os模塊提供了一個方便的walk()函式,它接受一個根路徑,并以元組的形式回傳給定路徑下所有子目錄的串列。該元組的第一個元素是該子目錄的路徑,第二個是所有檔案夾的串列,第三個是該子目錄中所有檔案的串列。
在迭代所有子目錄時,通過第三個元組元素中的所有檔案名的嵌套回圈允許您迭代每個子目錄中的所有檔案。瀏覽完所有檔案后,您可以使用 python 的with關鍵字簡單地讀取檔案內容。(該open函式的第二個引數告訴它您要讀取)
with open("path/to/file", "r") as f:
lines = f.readlines()
這允許您將所有行作為字串串列讀取到變數中lines。
同樣,您可以以幾乎相同的方式寫入檔案,但這次您需要將“w”指定為第二個引數,因為您希望對新檔案具有寫入權限。
with open("path/to/other_file", "w") as f:
f.writelines(["line1", "line2"])
此代碼將給定的行串列寫入檔案。假設您已經將現有檔案中的所有行讀入lines您可以簡單地使用串列切片獲取您需要的行:lines[22:]回傳從 list 的第 22 個元素開始的所有行lines。
因此,您可以寫入f.writelines(lines[22:])新檔案。
類似的東西應該適合你:
import os
#iterate all files from current directory
#you can overwrite the path (".") to suit your needs
for path, folders, files in os.walk("."):
for file in files:
name, extention = os.path.splitext(file)
# make sure only .XY files are affected
if not extention == ".XY":
continue
lines = None
# read lines from existing .XY file
with open(os.path.join(path, file), "r") as file:
lines = file.readlines()
# write all but the 22 first lines into a new file
with open(os.path.join(path, name) "_cut" extention, "w") as newFile:
newFile.writelines(lines[22:])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315075.html
上一篇:Python3.10match如何比較1和True?
下一篇:多次單擊按鈕時僅打開1個視窗
