【参考链接】https://blog.csdn.net/weixin_44999258/article/details/125322316
【问题】数据库导出的csv文件有1.8G,需对文件进行切割
【解决办法】
python脚本对csv文件进行切割
【操作方法】
1.根据参考链接内容,调整下代码如下
import csv
import os
#创建csv文件并写入指定内容
#定义结果文件的生成路径
#result_path = D:autotestpythonscriptcsv拆分
#准备10000行的csv作为样例,进行拆分
example_path = r"D:autotestpythonscriptcsvASSIST_YN_GRID_USER2.csv" # 需要拆分文件的路径
example_result_dir = r"D:autotestpythonscriptcsv
esult" # 拆分后文件的路径
with open(example_path, r , newline= ,encoding= utf-8 ) as example_file:
example = csv.reader(example_file)
i = j = 1
for row in example:
print(row)
print(f i 等于 {i}, j 等于 {j} )
# 每1000个就j加1, 然后就有一个新的文件名
if i % 10000 == 0:
j += 1
print(f 第{j}个文件生成完成 )
example_result_path = example_result_dir + example_result + str(j) + .csv
print(example_result_path)
# 不存在此文件的时候,就创建
if not os.path.exists(example_result_path):
with open(example_result_path, w , newline= ,encoding= utf-8 ) as file:
csvwriter = csv.writer(file)
csvwriter.writerow([ 这是一个表头 ])
csvwriter.writerow(row)
i += 1
# 存在的时候就往里面添加
else:
with open(example_result_path, a , newline= ,encoding= utf-8 ) as file:
csvwriter = csv.writer(file)
csvwriter.writerow(row)
i += 1
2.操作过程中遇到的问题
问题1:AttributeError: module ‘csv‘ has no attribute ‘reader‘
解决方法:由于python文件命名为csv.py,则需要修改文件名称为test.py,问题则解决
问题2:OSError: [Errno 22] Invalid argument
解决方法:读取文件出现了错误导致的。r”file”:意思是指为了避免xx是一个转义字符而导致的错误,也就是说加上r之后,“”里的就不再出现转义字符,编程纯的文件地址。
修改代码
example_path = D:autotestpythonscriptcsvASSIST_YN_GRID_USER2.csv # 需要拆分文件的路径
修改成
example_path = r"D:autotestpythonscriptcsvASSIST_YN_GRID_USER2.csv" # 需要拆分文件的路径
问题3:UnicodeDecodeError: gbk codec can t decode byte 0x80 in position 2: illegal multibyte sequence
解决方法:格式错误,修改代码
...
with open(example_path, r , newline= ) as example_file:
...
with open(example_result_path, w , newline= ) as file:
...
with open(example_result_path, a , newline= ) as file:
增加encoding= utf-8 ,修改成
with open(example_path, r , newline= ,encoding= utf-8 ) as example_file:
...
with open(example_result_path, w , newline= ,encoding= utf-8 ) as file:
...
with open(example_result_path, a , newline= ,encoding= utf-8 ) as file:
...
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...
