
python讀取txt字串 在 コバにゃんチャンネル Youtube 的最佳貼文

Search
Python 讀取txt 文字檔,一篇搞懂! · 最基本的讀檔寫法 · open 開啟檔案的幾種模式 · 一次讀取一行文字,逐步讀取 · 一次讀取全部的文字 · 使用try…except… ... <看更多>
我看到這裡有個並行的帖子,與我的不同的事,我要同時讀以及查詢同一個文件,上述鏈接可以並行操作多個文件。 with open('3.txt', 'r') as f3, ... ... <看更多>
讀取 檔案. 在python可以處理文字檔中的資訊,可以一次讀取全部的內容,也可以一行一行的讀取。 Python內建函式 open() 可以開啟指定檔案,可以讀取、寫入和修改檔案 ...
Python 讀取txt 文字檔,一篇搞懂! · 最基本的讀檔寫法 · open 開啟檔案的幾種模式 · 一次讀取一行文字,逐步讀取 · 一次讀取全部的文字 · 使用try…except…
#3. 讀取文字檔你不可不知的4種方式|Python新手入門教學[6]
此文章教大家使用4方式在python讀取txt file文字檔,包含fh.read()、fh.readline()、fh.readlines()、for i in fh(for迴圈讀取fh),想知的話我們就 ...
... 讀取檔案時,它也會讀取換行符 \n 。我們可以使用 replace() 函式來去掉該字元。此函式將用該函式中的指定字元替換字串中的所有換行符。 例如,. Python.
python讀取txt 檔案的方法:1、使用read()函數逐個位元組或者字元讀取txt檔案中的內容;2、使用readline()函數逐行讀取txt檔案中的內容;3、 ...
#6. Python檔案處理:如何建立文字檔案,讀取,寫入,開啟
txt ","w+"). 我們宣告變數”f”以開啟一個名為.txt的檔。Open 需要2 個引數,即我們要開啟的檔和一個字串,該字串表示我們要對檔執行的許可權或操作型別 ...
#7. python 檔案讀寫
讀寫txt 檔: · f.read(size): 將文字讀取成string(若換行會包含\n),其中size為要讀取長度,若不填則讀取全部。 · f.readline(): 讀取當下游標後的一行文字 ...
#8. [Pandas教學]Python 檔案讀取與寫入csv, txt教學與範例strip ...
[Pandas教學]Python 檔案讀取與寫入csv, txt教學與範例strip用法(with, open, rstrip, read, write, append) · 使用with讀取檔案 · 寫入檔案 · 總結 · 相關 ...
readline() 是另一個Python 內建的函式, 用法跟read() 差不多, 主要分別是每次執行只會讀取一行內容, 比較適合讀取大檔案。 例如檔案內容是這樣: Python
#10. 菜鳥工程師肉豬: Python 讀取文字檔案read text files
Python讀取 文字檔並印出內容範例如下。 Python可直接使用內建的 open() 函式來讀取或寫出檔案。 例如下面是要被讀取的文字檔 lyrics.txt 的內容, ...
#11. 7.2. 存取文字檔· ICE101-Basic Python programming and data ...
「開啟模式」是一個字串,可以來指定檔案類型及要做什麼樣的操作,此字串可以有一到二個字元。開啟開模式的第一個字元表示操作的類型:. r : 表示取讀。 w : 表示寫入 ...
#12. Python 如何實現並行查找關鍵字所在的行
我看到這裡有個並行的帖子,與我的不同的事,我要同時讀以及查詢同一個文件,上述鏈接可以並行操作多個文件。 with open('3.txt', 'r') as f3, ...
#13. Python-64-Files檔案3.讀取檔案內容| Yiru@Studio
讀出檔案內容讀取幾個字只讀第一行把資料轉成陣列後讀出使用for 迴 ... Python-11字串處理-抓取字串中的字元、計算字數len()、字母轉大小寫lower ...
#14. 內建函式( 檔案讀寫open ) - Python 教學 - STEAM 教育學習網
範例的程式碼執行後,會回傳目前讀取檔案指針的位置( 檔案從頭算起的字元數)。 f1 = open('/content/drive/MyDrive/Colab Notebooks/test.txt','r') ...
#15. [Python] 讀取文字檔TXT (分行讀取與分割字串) - 程式人- 痞客邦
f = open('test.txt', 'r'). lines = f.read().splitlines() #分行讀取. lst = [ln.split(' ')[0] for ln in lines] #依據空格做切割字串,並只取第一 ...
#16. Python读取txt文件的三种方式原创
文本处理是经常碰到的一个问题,Python的文本读取有三个方法可以调用:read()readaline()readlines()直接看名字就大概能猜出什么意思。
#17. How can I read a text file into a string variable and strip ...
You could use: with open('data.txt', 'r') as file: data = file.read().replace('\n', ''). Or if the file content is guaranteed to be one line ...
#18. Python 文字檔案的讀取和儲存By 彭彭 - YouTube
讀取 檔案2.1 一次 讀取 全部:read() 2.2 逐行 讀取 資料:使用for 迴圈3. 寫入檔案3.1 寫入 字串 到檔案中:write( 字串 ) 3.2 寫入換行符號:\n 4. 讀取 ...
#19. 【python】讀取和輸出到txt - 麥可code
read() #一次性讀取文字中全部的內容,以字串的形式返回結果. with open("test.txt", "r") as f: #開啟檔案 data = f.read() #讀取檔案 print(data).
#20. 7. 輸入和輸出— Python 3.10.12 說明文件
f.readline() 從檔案中讀取單獨一行;換行字元( \n )會被留在字串的結尾,只有當檔案末端不是換行字元時,它才會在檔案的最後一行被省略。這種方式讓回 ...
#21. python怎么读取txt文件内容为str字符串(python中如何读 ...
f.readlines():将以列表的形式返回该文件中包含的所有行,列表中的一项表示文件的一行。如果设置可选参数sizehint, 则读取指定长度的字节, 并且将这些字 ...
#22. 13.Python 文字檔案的讀取和儲存By 彭彭
with open(“data.txt”, mode=“r”, encoding=“utf-8”) as file: data=file.read ... Python 數字、字串的基本運算By 彭彭4.Python 有序列表的基本運算- List、Tuple ...
#23. Python读取文件内容为字符串的方法(多种方法详解)
py文件调用,或一个常规的txt文件),我们去取那个数据的方法也是多样的。 知识点补充:python读取txt文件中字符串,字符串用空格分隔 ... jsp"); // 读取WebRoot下String ...
#24. 利用Python讀取txt檔案的方法講解- IT閱讀
附:全部的轉義字元和含義:. 以上這篇利用Python讀取txt文件的方法講解就是小編分享給大家的全部內容了,希望能給 ...
#25. Python字串(string)基礎與20種常見操作
用哪一種引號來表示字串比較好? 只想用一種引號?轉義字元可以幫你; 字串的20種操作. 使用Str() 函式來建立 ...
#26. python 读取txt特定内容
目的在于读取TXT文件,并截取两个(字符串str/数字/符号等)关键字之间的内容(数据/字符串等),转为datafram格式,再更改行,列名写入csv中。
#27. Python读取txt文件有几种方法,区别在哪?
可以看到,输出的数据为bytes 字节串。我们可以调用decode() 方法,将其转换成我们认识的字符串。 Python readline()函数. readline() 函数用于读取 ...
#28. Python學習筆記8-文件的讀取和寫入
... 讀取一行數據,或者使用readlines()方法來讀取所有行數據,這些方法都會返回一個字串或者一個列表。 讀取整個文件. f = open("test.txt", "r") content ...
#29. File IO 檔案讀寫
read() 讀取檔案¶. The read() method reads a string from an open file. It is important to note that Python strings can have binary data, not only text ...
#30. PYTHON程式語言的學習-5
每次讀進一行,直到檔案的末了。變數i是字串。 FL = open('readin-1.txt','r') for i in FL: print ...
#31. 小狐狸事務所: Python 學習筆記: 檔案存取(一) 讀寫文字檔
此語法是在內縮區塊處理讀寫, 結束後不須呼叫f.close(), 它會自動關閉檔案. open() 的必要參數filename 為包含路徑之檔案名稱(字串), 例如'test.txt', ' ...
#32. 一文教你学会python读取文本及字符串常用操作
Python 的文本处理是经常碰到的一个问题,Python的txt文件读取中,有三类方法:read()、readline()、readlines(),这三种方法各有利弊,下面逐一介绍其使用 ...
#33. python怎麼讀取txt檔案?
... 字串。以上就是用python將txt檔案讀取到一個字串里程序的演示:. 2 # 我是阿嘛. 可以看一下簡單的pyhton檔案操作,給出一個最簡單的例子. 只讀方式開啟 ...
#34. Python 读取写入txt文本文件内容及简单记录日志
1、读取txt文本 · 1)read(). read() 一次性读取全部txt文本内容,一次性读取文本中全部的内容,以字符串的形式返回,具体如下, · 2)readline(). readline ...
#35. 【open】python使用open直接對文件(txt csv jpg html ...)取代 ...
先使用open打開你要變更的檔案,而後使用read()方法讀取裡面內容,. 此時為 ... python使用open直接對文件取代指定字串. 三、後記. python因為各種套件很 ...
#36. 請益#請益Python 讀取.txt檔內容- 軟體工程師板
... Python寫一個讀取字串的工具,並且逐行讀取(從第一行讀到最後一行),舉例來說,當該行讀取到字串「身份證字號有一的同學」的時候,印出「1」;而當 ...
#37. Python 读取txt 文档中特定字符串之间的字符串 - 小焱
import re #文本所在TXT文件#获得xs.txt 中的参数。 file = 'xs.txt' f = open(file, 'r') buff = f.read() #关键字1,2(修改引号间的内容) Mark_SN1 ...
#38. 1 一、開啟檔案二、寫入檔案
若覺得跳脫字元麻煩,可在檔案路. 徑前,加入「r」。 例如:. 檔案物件名稱= open("C:\\slhs\\test.txt", "存取模式").
#39. TQC-Python 系列文章Yiru@Studio - - 點部落
txt 檔案, 我們需要寫一個程式去讀取這個檔案檔案內容是一串數字,每個數字間都用空白分隔所以要把這串數字一個個先切割出來存到陣列後再把這些字串 ...
#40. Python 檔案讀取file.read(), file.readlines()返回2D list,n也會 ...
最末可以少打. file.close(). “”” · 差別是.readlines(). \n的換列字元也會涵蓋. 而且回傳一個list · “”” “””.
#41. python读取txt数据的操作步骤
关键字with在不需要访问文件时将其自动关闭。读取出的内容以字符串形式保存在data1/data2里. (2)第一种:读取所有行infile.readlines(). (3)第二种 ...
#42. python读取txt特定内容
在Python 中读取txt 文件并获取特定内容需要用到以下几个步骤:. 打开文件:使用Python 内置的open() 函数打开文件。 读取文件:使用read() 或readlines() 方法读取 ...
#43. python中读取txt文件时split()函数的妙用
不知道大家有没有过需要从txt文件中读取含有多行多列的数据的经历,当我们读入数据时,数据会以string的形式被读入,然而如何进行数据类型转换就成了 ...
#44. Python for Beginners (18)|檔案處理(File Handling)
file_1.read() 會讀取demo.txt 內的資料,並且儲存至read_content 變數中。 範例4:讀出檔案指定數量字元. 範例4 為讀出檔案中的前7 個字元,包含空格。
#45. TQC+-程式語言Python 3-09第九類
說明: 請撰寫一程式,要求使用者輸入檔名read.txt,顯示該檔案的行數、單字數(簡單起見,單字以空白隔開即可,忽略其它標點符號)以及字元數(不含空白)。 檔案連結...
#46. Python文件I/O - Python教學 - 極客書
raw_input([prompt])函數從標準輸入讀取一行並返回一個字符串(去掉結尾的換行)。 #!/usr/bin/python str = raw_input("Enter your input: "); ...
#47. 【已解決】【問題】讀取的檔案跟原先的資料不同
... 讀取錯誤,第一欄位應該是字串,但我執行後字串變在最後面,讀取資料的數值也是不對的。 麻煩幫忙解惑了,謝謝~ 資料型態:(txt ... 問題請教python爬蟲 ...
#48. 利用Python處理字串、字元全攻略
... Python處理字串、字元全攻略:抓取字串中的第幾個字, ... 任務7-2:實作整理字串後讀出. 資料為:"0912569369-John-Taipei-09:02 ...
#49. C++ -讀取txt 文字檔中文亂碼問題- 小哈的程式工作坊
windows 以前txt 檔的預設編碼是ansi,windows 10 之後預設編碼變成了utf8。 2. C++ 裡可以處理的字串編碼只有ansi 和unicode,沒有utf8。 3. console 的命令提示字元 ...
#50. 使用C# 逐行讀取文件
string text = File.ReadAllText(fileName);. string ... 以下代碼使用流閱讀器打開文本文件,將內容複製到字符串,然後使用換行符作為分隔符拆分字符串 String.Split() 方法 ...
#51. 快速入門: (Python) 讀取Azure 事件中樞擷取的資料
執行指令碼. 開啟在其路徑中具有Python 的命令提示字元,並執行下列命令來安裝Python 必要條件封裝︰.
#52. Python程式語言part2
txt ,要讀取這個檔案,使用以下指令. ▻ 2. open ... ▻ 取得環保署空氣品質監測網頁表頭及內容。 ▻ 取得網頁內容後,在看你要如何處理或擷取特定字串或資.
#53. Lesson 02 將數據檔案讀進程式內Read data from file
... txt', dtype='float'); 用sp函式庫中的genformatxt來讀取檔案workfile, 把workfile的內容以字串的str的格式存入Data中, 當然dtype也可以指定其他格式, 例如整數'int'或 ...
#54. Python - 如何打開檔案與讀取檔案 - 醬流's Blog
也能透過其他字串判斷的function,找出自己要的檔案。 因此會變成:. import os for file in os.listdir("/Users/JohnLiu/CodeProject/codes/Documents"): ...
#55. python读写txt文件字符串
txt 文件名称1.txt. txt 文件内容. openbrower|chrome. visit|https://wxtest.9fbank.com/h5/#/. 打开txt文件. with open(file="1.txt",mode='r') as test: txt 读取 ...
#56. 檔案操作- Python
請注意,在第2行的字串中最後面那個「\n」的符號是換行記號,沒有這行的話,後面 ... 讀取出來呢?同樣也是使用open函數開啟檔案,在取得檔案物件之後,就可以利用read ...
#57. Python 與中文處理
使用Unicode 來表達中文字串,Python 才能在字串的索引中,簡便而正確地 ... 在Python 程式中,讀入中文文字檔案時,也要事先知道該檔案的編碼方式 ...
#58. [C 語言] 字元輸入輸出、文件讀寫
假設我們在當前目錄底下有份檔案file.txt,內容為: Today is a nice day. I want to go to play. 那麼我們可以使用fopen() 讀取這份檔案。
#59. 看板Python - Re: [問題] 抓取txt特定內容並作註解or計算
獲取數值可以用re.split簡單達成填入文字本來想要用f-string加上\t間隔來排版發現國字的全形和數字的半形在同一欄時,很難讓欄位對齊所以做了一點細部 ...
#60. Python 檔案內搜索固定位置字串並取代文字
read() #將檔案讀成字串 idFilter = 'Name="ID" Value=' #搜索檔案內特定 ... txt", "r+") fileaString = filea.read() idFilter = 'cde' idPosition ...
#61. 路徑小幫手- pathlib
是說,在寫Python的時候,有時候會需要讀取(或寫入)檔案吧? ... 不然的話,你可能得用像這樣的寫法(加一個r 在string之前)來提供原始字串(raw string ...
#62. [Python教學]Python字串實用技巧
字串 裁切就是基於原字串取出想要的部分,像是想存取字串中特定位置的字元,在Python中使用[] 符號,並傳入索引值。特別注意索引值由0開始計算。 如果想從字串的最後一個 ...
#63. [python] [VI coding] 第十四章檔案處理- 教學區
readlines()會回傳所讀取之字串,一行是一個元素。 註1. 後兩個方法僅用在文字檔,因使用者輸入才有換行字元問題。 註2.
#64. 說說在Python 中,如何讀取文件中的數據
... 讀取我們想要讀取《傲慢與偏見》txt小說:file='novel。我們只管打開文件使用它即可,Python ... rstrip() 函數會刪除string 字符串末尾的空格。 4 在with ...
#65. Python 读取txt文本文件
read() //file_context是一个string,读取完后,就失去了对test.txt的文件引用 # file_context = open(file).read().splitlines() // file_context是 ...
#66. Python怎么读取txt文件?(python怎么读取txt文件)
本篇文章将给大家介绍Python读取TXT文件的方法,有需要的朋友可以参考一下:一、读文件1.简单的将文件读取到字符串中f = open(
#67. python web開發-flask中讀取txt檔案內容
python web開發-flask中讀取txt檔案內容. 最後更新:2018-03-22 來源:互聯網 ... python:發送郵件 · python CMDB開發 · python學習筆記1-賦值與字串 · python學習筆記2-列(list) · Python中的底線的用法 ...
#68. How to read File as String in Python
To read file content to string in Python: 1. Open file in text or read mode. It returns a file object. 2. Call read() method on the file object.
#69. Python 從標準輸入讀取資料教學與範例
fileinput.input 會自動將所有命令列所指定的參數( sys.argv[1:] )視為輸入檔案,將這些檔案內容串 ... txt 的檔案內容 python3 script5.py lines.txt line1 line2 line3 ...
#70. TQC+ 程式語言Python 906 字串資料取代
檔案下載: data.txt. 程式碼:. f_name = input() str_old = input() str_new = input() file = open(f_name, 'r+') datas = file.read() print("=== ...
#71. Re: [問題] 抓取txt特定內容並作註解or計算- 看板Python
獲取數值可以用re.split簡單達成填入文字本來想要用f-string加上\t間隔來排版發現國字的全形和數字的半形在同一欄時,很難讓欄位對齊所以做了一點細部 ...
#72. How to Read a Text file In Python Effectively
This tutorial shows you how to read a text file in Python effectively. It shows you various ways to read a text file into a string or list.
#73. 使用Python對檔案(File)進行讀寫操作等的相關操作:Read, ...
glob函數的話,因可以使用萬用字元,所以能做出條件刪選,像是指定檔案的類型。 檔案名稱的變更. 使用 os 模組的rename函數可以更改檔案的名稱。 import ...
#74. python 讀檔
在Python 中,我們有內建函式可以處理不同檔案型別的檔案操作。. 文字檔案包含系列字串,其中本篇介紹python 讀取txt 文字檔的方法,python 讀檔是 ...
#75. Python - 讀取.txt檔案並存成1D array 或2D array
... read().split(",") # String用","分割成list # newList = DD.split(",") newList = f.read().split(",") CC = np.concatenate((CC ,newList),axis=0) ...
#76. [python] 讀取文字檔中的數字轉換為numpy陣列
2. 由python讀取檔案,並將其值指派到numpy array. 3. 最後透過Matplotlib進行視覺化. 程式碼. import numpy as np filename = 'number.txt' elements ...
#77. PERL一次讀取檔案所有內容的方法($/)
txt ' ) or die "$!" ;. print FILE "這是加在最前面的一行" ;. print FILE ... 2. 一次讀取全部字串才能做跨行的比對,比傳統檔案全部讀完再相粘的方法 ...
#78. 請問如何將讀入的txt檔案變成dataframe?
找到換行符號,用該符號做字串分割後,把它拿掉split_tag = " ... 請問我知道需要分割\n 和\t 所讀取的網址才會是完整的。 但程式上分割過一次 ...
#79. python 讀檔
... python讀取txt file文字檔,包含fh.read 、fh.readline 、fh.readlines ... mode: mode 開啟檔案的模式字串型態、可以省略,預設為讀取r 。 通常都是 ...
#80. TQC+ 程式語言Python 906 字串資料取代
請撰寫一程式,要求使用者輸入檔名data.txt、字串s1和字串s2。程式將檔案中 ... 被讀取的檔案和撰寫程式時的.py檔,必須放在同一個目錄下). fname,s1,s2 ...
#81. Python 讀取與寫入CSV 檔案教學與範例
這裡在開啟csv 檔案時加上了 newline='' 參數,這是為了讓資料中包含的換行字元可以正確被解析,所以建議在讀取csv 檔案時都固定加入這個參數。 指定分隔 ...
#82. [Python] 檔案讀寫
file.readline(). 讀取檔案中的整行內容,但一次只讀取一行,包含 \n 字元,若檔案內容 ...
#83. Reading and Writing to text files in Python
There are three ways to read data from a text file. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified ...
#84. Read a file line by line in Python
Create a list L with three string elements containing newline characters. Open a file named myfile.txt in write mode and assign it to the ...
#85. Python split()方法| 菜鸟教程
str.split(str="", num=string.count(str)). 参数. str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\ ...
#86. Fasta to csv python online. This means it would be possible ...
py","contentType":"file python将txt转为csv格式; Python:将fastq文件转为fasta ... Just like a normal string in python, sequence objects also have a 'count ...
#87. File Handling in Python – How to Create, Read, and Write ...
Based on the file we have created above, the below line of code will insert the string into the created text file, which is "myfile.txt.” file.
#88. Python File Open
To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file ...
#89. IO tools (text, CSV, HDF5, …) — pandas 2.1.0 documentation
If using 'zip', the ZIP file must contain only one data file to be read in. Set to ... dtypes Out[34]: a Int64 b Float64 c boolean d string[python] e Int64 f ...
#90. Python Strings | Python Education
To convert a regular Python string to bytes, call the encode() method on the string. ... text file with some encoding and read out unicode strings ...
#91. How To Read A CSV File In Python - Earthly Blog
The open() method takes two arguments of type string . First the file name, and second a mode argument. We are using r for read, however ...
#92. Strings and Character Data in Python
Read on for more information about built-in string methods! Built-in String Methods. You learned in the tutorial on Variables in Python that Python is a ...
#93. Python JSON: Read, Write, Parse JSON (With Examples)
If the file doesn't already exist, it will be created. Then, json.dump() transforms person_dict to a JSON string which will be saved in the person.txt file.
#94. How To Remove Spaces from a String In Python
This tutorial provides examples of various methods you can use to remove whitespace from a string in Python. A Python String is immutable, so ...
#95. numpy.loadtxt — NumPy v1.25 Manual
Data read from the text file. See also. load , fromstring , fromregex ... The strings produced by the Python float.hex method can be used as input for floats.
#96. Connection String URI Format
... TXT record by passing the option in the query string. In the following ... These parameters allow you to specify read preferences on a per-connection basis in the ...
#97. 04-3 파일 읽고 쓰기 - 점프 투 파이썬
만약 역슬래시( \ )를 사용한다면 "C:\\doit\\새파일.txt" 처럼 역슬래시를 2개 사용하거나 r"C:\doit\새파일.txt" 와 같이 문자열 앞에 r 문자(raw string)를 덧붙여 ...
#98. 微軟應用Transformer模型開發之生成式AI「程式碼自動完成 ...
至於大型的訓練資料集,則來自如GitHub或其他程式碼儲存庫中的各種程式語言(例如C、Java、Python ... 取權杖(access token)或其他形式的識別字串。 (4)區塊 ...
#99. Python Read File and Python Write to File
Then the in-built function for writing into the file object will take care of the rest. 1. write(string). This function takes a string as an argument and writes ...
python讀取txt字串 在 看板Python - Re: [問題] 抓取txt特定內容並作註解or計算 的推薦與評價
獲取數值可以用re.split簡單達成
填入文字本來想要用f-string加上\t間隔來排版
發現國字的全形和數字的半形在同一欄時,很難讓欄位對齊
所以做了一點細部的調整
大致的流程是獲得文本list之後,對需要修改的行位做修改,再全部黏起來('\n'.join)覆寫回去
Before:
After:
程式碼:
import re
#設定文字檔路徑
txt_filepath='path/to/data.txt'
#定義動作:在文字行的串列中獲取兩個虛線的行索引
def GetDashlineRowIndexes(line_list):
i_dashline_row1=None #第一條虛線的行索引
i_dashline_row2=None #第二條虛線的行索引
#逐行搜尋
for i_row,line_text in enumerate(line_list):
#判定有10個以上的虛線字元即為虛線行
if '-'*10 in line_text:
if not i_dashline_row1:
i_dashline_row1=i_row
else:
i_dashline_row2=i_row
break
#若兩條的虛線都有找到
if all([i_dashline_row1,i_dashline_row2]):
return i_dashline_row1, i_dashline_row2
#若兩行的虛線有其中一條未找到
else:
raise ValueError('文字檔應至少包含兩個虛線行')
#定義動作:將單行的數據文字串列輸出為單行等寬欄的字串
def RowDataListToOneLine(row_data_list):
#設定固定欄寬
space_len=8
#生成新的單行文字內容
new_line=''
for row_data in row_data_list:
#計算全形字的數量
num_of_fullwidth_chr=sum(ord(s)>126 for s in row_data)
#使用f-string排版,設定向右對齊(根據全形字的數量去教準)
new_line+=f'{row_data:>{space_len - num_of_fullwidth_chr}}\t'
return new_line
#讀取所有txt文字
with open(txt_filepath,'r',encoding='utf-8') as f:
text=f.read()
#分割每一行內容做成list
line_list=text.split('\n')
#獲取兩個虛線的行索引值
i_dashline_row1, i_dashline_row2 = GetDashlineRowIndexes(line_list)
#處理標題列文字行,先獲取標題列的行索引
i_header_row=i_dashline_row1 - 1
#獲取單行標題列文字並分割為串列
header_line=line_list[i_header_row]
row_data_list=re.split(r'\s+',header_line.lstrip())
#將原標題列字串替換為等寬欄的字串
line_list[i_header_row]=RowDataListToOneLine(row_data_list)
#處理數據列文字行
for i_row in range(i_dashline_row1+1, i_dashline_row2):
#獲取單行的數據文字串列
row_data_list=re.split(r'\s+',line_list[i_row].lstrip())
#取左邊10欄
row_data_list=row_data_list[:10]
#取得各項數值
W,X,Y,Z,W_w,X_w,Y_w,Z_w=(float(data) for data in row_data_list[2:])
#計算均重,輸出文字格式:取至兩個小數點並向右對齊(若分母為零則顯示0.00)
W_avg=f'{W_w/W:>.2f}' if W else '0.00'
X_avg=f'{X_w/X:>.2f}' if X else '0.00'
Y_avg=f'{Y_w/Y:>.2f}' if Y else '0.00'
Z_avg=f'{Z_w/Z:>.2f}' if Z else '0.00'
#將原數據列字串替換為等寬欄的字串
line_list[i_row]=RowDataListToOneLine(row_data_list +
[W_avg,X_avg,Y_avg,Z_avg])
#重新組成text內容
new_text='\n'.join(line_list)
#覆寫檔案
with open(txt_filepath,'w',encoding='utf-8') as f:
f.write(new_text)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.216.6.172 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1581057249.A.E3A.html
※ 編輯: papple23g (61.216.6.172 臺灣), 02/07/2020 14:41:13
... <看更多>