使用Python在csv中添加新行 [英] Add new row in csv with Python

查看:2765
本文介绍了使用Python在csv中添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想在每个帖子请求的CSV中添加一行。但是,第一篇文章很好。第二个帖子突然增加了2行(新的和现有的一行),第三个帖子增加了3行等。如何解决这个问题?



什么我试过了:



  def  post(self ,request,format = None):
user = MyUser.objects.get(user = request.user)
movie = Movie.objects.get(movieId = request.POST [' movieId'])
rating = Rating(ratingValue = request.POST [' ratingValue'],movie = movie,user = user)
rating.save()

< span class =code-keyword> 打开(' data / train.csv'' a' as csvfile :
spamwriter = csv.writer(csvfile)
spamw riter.writerow([user.userID,request.POST [' ratingValue'],int(round(round) time.time(), 0 ))])

return 响应( status = status.HTTP_200_OK)

解决方案

参见 13.1。 csv - CSV文件读取和写入 - Python 2.7.12文档 [ ^ ]。

So I am trying to add a line in my CSV for every post request. However, the first post is fine. The second post suddenly adds 2 rows (the new and the existing one), the third post adds 3 rows etc. How do I fix this?

What I have tried:

def post(self, request, format=None):
        user=MyUser.objects.get(user=request.user)
        movie = Movie.objects.get(movieId=request.POST['movieId'])
        rating = Rating(ratingValue=request.POST['ratingValue'], movie=movie, user=user)
        rating.save()

        with open('data/train.csv', 'a') as csvfile:
            spamwriter = csv.writer(csvfile)
            spamwriter.writerow([user.userID, request.POST['ratingValue'], int(round(time.time(),0))])

        return Response(status=status.HTTP_200_OK)

解决方案

See 13.1. csv — CSV File Reading and Writing — Python 2.7.12 documentation[^].


这篇关于使用Python在csv中添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆