【问题标题】:Delete '\n' from values of dictionary从字典的值中删除 '\n'
【发布时间】:2021-06-27 19:40:24
【问题描述】:

如何从字典中的值中删除“\n”?

files_dict = {}
for file in os.listdir("C:/Users/kk/Desktop/e"):
    if file.endswith(".txt"):
        key = file.split(".")[0]
        
        full_filename = os.path.join("C:/Users/kk/Desktop/e", file)
        with open(full_filename, "r") as f:
            files_dict[key] = f.readlines()

pprint.pprint(files_dict)

value_list1 = files_dict['f1']
print('Values of f1 are:')
print(value_list1)

输出

Values of f1 are:
['1\n', '2\n', '3\n']

【问题讨论】:

  • 你能提供你目前得到的输出吗?

标签: python-3.x file dictionary newline


【解决方案1】:

试试这个。 .readlines() 返回每​​一行的列表,包括终止的换行符。 .read().split('\n') 将读取所有数据,并将其拆分为换行符上的列表。

files_dict = {}
for file in os.listdir("C:/Users/kk/Desktop/e"):
    if file.endswith(".txt"):
        key = file.split(".")[0]
        
        full_filename = os.path.join("C:/Users/kk/Desktop/e", file)
        with open(full_filename, "r") as f:
            files_dict[key] = f.read().split('\n')
## Heading ##
pprint.pprint(files_dict)

value_list1 = files_dict['f1']
print('Values of f1 are:')
print(value_list1)

【讨论】:

  • Python 默认将所有换行符类型转换为\n
  • @chepner 有趣!相应地编辑
【解决方案2】:

请使用默认的 file.read().splitlines() 无需重新启动轮子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多