删除整个Excel工作表(CSV逗号分隔)的最简单方法是什么?将工作表覆盖为空白也可以。
我需要这是自动化的。它应该删除此循环末尾的工作表。
到目前为止我的代码如下:
file_name =r'C:\Users\Trading\Desktop\scott\test.csv'
while True:
df=pd.read_csv(file_name, header=None, encoding="latin1")
if file_name is not "":
df=pd.read_csv(file_name, header=None)
lastRow = df.iloc[-1]
stock=(lastRow[0])
price=(lastRow[3])
print (stock, action, num_shares, price)
os.remove(file_name)
#csv_file.unlink() #I also tried this way..
print("file deleted")
更新错误消息
现在我收到错误UnicodeDecodeError:'utf-8‘编解码器无法解码位置18处的字节0xa0 :起始字节无效。
发布于 2019-06-26 04:27:23
我最好的猜测是,如何遍历包含多个csv文件的目录,读取和处理每个文件,然后删除它?我首先要说的是,您应该在运行此代码之前备份整个文件夹(并可能编写代码来为您执行此备份):
import pandas as pd
from pathlib import Path
folder = Path("C:/Users/Trading/Desktop/scott")
# Loop through all the csv files in the folder
for csv_file in folder.glob("*.csv"):
# read and process the files
df = pd.read_csv(csv_file, header=None)
stock = df.iloc[-1, 0]
price = df.iloc[-1, 3]
print(stock, price) # Do you really only want to print? You don't want to save this data somewhere permanent???
# Permanently delete the file
csv_file.unlink()
请注意,os.remove()
会工作得很好。但是从Python3.4开始,在python (而不是os
)中,pathlib
是处理文件的正确方式。您可以使用pathlib
使用.unlink()
方法删除文件。
我省略了ib
、numshares
和action
,因为您从未在代码中定义过它们……
https://stackoverflow.com/questions/56761296
复制相似问题