我有一些代碼可以讓我打開目錄中的所有 csv 檔案并運行它們,洗掉每個檔案的前 2 行,理想情況下,在此程序中,我希望它還在新的第一行末尾添加一個逗號(最初的第 3 行)
另一種可能的方法是洗掉每個 csv 中出現的所有其他行上的尾隨逗號。
任何想法或方法將不勝感激。
import glob
path='P:\pytest'
for filename in glob.iglob(path '/*.csv'):
with open(filename, 'r') as f:
lines = f.read().split("\n")
f.close()
if len(lines) >= 1:
lines = lines[2:]
o = open(filename, 'w')
for line in lines:
o.write(line '\n')
o.close()
uj5u.com熱心網友回復:
在那里添加一個計數器可以解決這個問題:
import glob
path=r'C:/Users/dsqallihoussaini/Desktop/dev_projects/stack_over_flow'
for filename in glob.iglob(path '/*.csv'):
with open(filename, 'r') as f:
lines = f.read().split("\n")
print(lines)
f.close()
if len(lines) >= 1:
lines = lines[2:]
o = open(filename, 'w')
counter=0
for line in lines:
counter=counter 1
if counter==1:
o.write(line ',\n')
else:
o.write(line '\n')
o.close()
uj5u.com熱心網友回復:
您的代碼的一個可能問題是您正在將整個檔案讀入記憶體,這可能很好。如果您正在讀取較大的檔案,那么您希望逐行處理檔案。
最簡單的方法是使用 fileinput 模塊:https ://docs.python.org/3/library/fileinput.html
像下面這樣的東西應該可以作業:
#!/usr/bin/env python3
import glob
import fileinput
# inplace makes a backup of the file, then any output to stdout is written
# to the current file.
# change the glob..below is just an example.
#
# Iterate through each file in the glob.iglob() results
with fileinput.input(files=glob.iglob('*.csv'), inplace=True) as f:
for line in f: # Iterate over each line of the current file.
if f.filelineno() > 2: # Skip the first two lines
# Note: 'line' has the newline in it.
# Insert the comma if line 3 of the file, otherwise output original line
print(line[:-1] ',') if f.filelineno() == 3 else print(line, end="")
uj5u.com熱心網友回復:
我添加了一些編碼,而我的卻拋出了一個錯誤,但編碼很好地修復了它
import glob
path=r'C:/whateveryourfolderis'
for filename in glob.iglob(path '/*.csv'):
with open(filename, 'r',encoding='utf-8') as f:
lines = f.read().split("\n")
#print(lines)
f.close()
if len(lines) >= 1:
lines = lines[2:]
o = open(filename, 'w',encoding='utf-8')
counter=0
for line in lines:
counter=counter 1
if counter==1:
o.write(line ',\n')
else:
o.write(line '\n')
o.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428814.html
