【问题标题】:Appending data in csv file problems在 csv 文件中追加数据问题
【发布时间】:2018-08-03 10:19:47
【问题描述】:
def append(new)
     user_file = open(r'users.csv', "a", newline = '')
     writer = csv.writer(user_file)
     writer.writerows(new)


#create a user list[... , ...]
append(user)

我尝试在 CSV 文件中追加行,我的列表中可以包含正确的数据。但是,我的 CSV 文件中的数据有问题。

我在 CSV 文件中的原始内容:

admin, abcd
user1, qwer

我希望我的 CSV 文件在运行后应该是这样的:

admin, abcd
user1, qwer
appenduser, appendpassword

但是,在运行我的程序后,我的 CSV 文件会像这样附加:

admin, abcd
user1, qwer

a,p,p,e,n,d,u,s,e,r
a,p,p,e,n,d,p,a,s,s,w,o,r,d

我应该怎么做才能解决我的问题?感谢您的帮助!

【问题讨论】:

  • writerows 遍历参数,因此它会遍历字符串,如果这是你正在通过的,我建议在函数内打印 new 看看你是否真的在通过你打算通过什么(不清楚)

标签: python python-3.x csv


【解决方案1】:

使用writerow

例如:

def append(new):
     user_file = open(r'users.csv', "a", newline = '')
     writer = csv.writer(user_file)
     writer.writerow(new)    

#create a user list[... , ...]
append(user)

【讨论】:

  • 感谢您的帮助,它确实有效。追加新数据后的换行符怎么样?我该如何避免呢?
  • 如果我使用 ab 而不是 a 会抛出错误(二进制模式不接受换行参数)
  • 只是user_file = open(r'users.csv', "ab")?
  • 另一个错误,需要一个类似字节的对象,而不是'str'
  • 我找到了解决方案。我使用 users_file = open(r'users.csv', "a", newline='\n') 并且它有效。
猜你喜欢
  • 1970-01-01
  • 2017-08-12
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2021-07-01
  • 2022-11-10
  • 1970-01-01
相关资源
最近更新 更多