gpt4 book ai didi

python - 使用 python 删除桌面上的 CSV 工作表(出现错误 UnicodeDecodeError : 'utf-8' )

转载 作者:行者123 更新时间:2023-12-01 00:48:25 25 4
gpt4 key购买 nike

删除整个 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: 无效的起始字节。

最佳答案

我对您所问问题的最佳猜测是如何循环遍历包含多个 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() 会工作得很好。但从 python 3.4 开始,pathlib是在 python(而不是 os)中处理文件的正确方法。您可以使用 .unlink() 方法删除带有 pathlib 的文件。

我遗漏了 ibnumsharesaction 因为您从未在代码中定义它们...

关于python - 使用 python 删除桌面上的 CSV 工作表(出现错误 UnicodeDecodeError : 'utf-8' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56761296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com