python - 如何从 csv 文件中删除换行符?
问题描述
如何从我的 csv 文件中删除换行符?这是我当前输出的样子:
{'\n': ('', ''), '0-586-08997-7\n': ('Kurt Vonnegut', 'Breakfast of Champions'), '978-0-14-302089-9\n': ('Lloyd Jones', 'Mister Pip'), '1-877270-02-4\n': ('Joe Bennett', 'So Help me Dog'), '0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}
这就是输出的样子:
{'0-586-08997-7': ('Kurt Vonnegut', 'Breakfast of Champions'),
'978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip'),
'1-877270-02-4': ('Joe Bennett', 'So Help me Dog'),
'0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}
我不想使用任何内置的 csv 工具或任何其他工具,因为我们还没有在课堂上做过这些,所以我怀疑我们是否需要在这些问题中使用它们。
def isbn_dictionary(filename):
"""docstring"""
file = open(filename, "r")
library = {}
for line in file:
line = line.split(",")
tup = (line[0], line[1])
library[line[2]] = tup
return library
print(isbn_dictionary("books.csv"))
解决方案
对您的代码进行最少的修改:
def isbn_dictionary(filename):
"""docstring"""
file = open(filename, "r")
library = {}
for line in file:
line = line.split(",")
if line[0]: # Only append if there is a value in the first column
tup = (line[0], line[1])
library[line[2].strip()] = tup # get rid of newlines in the key
file.close() # It's good practice to always close the file when done. Normally you'd use "with" for handling files.
return library
print(isbn_dictionary("books.csv"))
空字符串是falseylibrary
,因此如果一行的第一个条目为空白,这将不会添加到您的dict 中。
推荐阅读
- python - Python 抓取网站 w/BeautifulSoup4 显示具有类名的表的属性错误
- wordpress - 如何从特定类别中提取最新帖子
- java - 这是用 java 12 编写的,但如果我在 java 15 上运行它,它会引发异常错误
- python - 如何替换 tf.train.batch ,因为它已被弃用
- c++ - 从多个模板类参数中推导可变模板
- vba - 如何在 MS Word vba 中取消选择形状?
- javascript - 为导入添加 .js 扩展名
- reactjs - 将 props 传递给 PrivateRoute 组件
- java - Java Spring @MappedSuperclass 字段作为子类中的@Id 字段
- node.js - 多嵌套数组中的MongoDB更新对象