【问题标题】:Removing enter from every line of file从文件的每一行中删除输入
【发布时间】:2019-11-27 19:53:27
【问题描述】:

我是 Python 新手。有没有办法将文件的内容更改为我想要的方式? 这是我的txt文件

work
money
apple
dog

我想把它改成

work money apple dog

我不知道如何将它们放在一条线上,其余的对我来说很清楚 我现在的代码

fn = 'settings.txt'
f = open(fn)
for line in f:
  f.join(f.read().splitlines())

【问题讨论】:

  • 你卡在哪里了?您逐行阅读这些项目,然后将它们连接起来。使用+join。写出结果字符串。
  • 我已经打开了文件,现在卡在 for line in f(这是打开的文件)
  • 欢迎来到stackoverflow!还请按照@Prune 的建议提交一些您尝试过的代码。你可以看看how to create a minimal working example
  • 好的,我已经编辑了我的帖子

标签: python text operating-system


【解决方案1】:

这行得通:

with open('file_path') as f_1:
    res_str = ' '.join(f_1.read().splitlines())

【讨论】:

    【解决方案2】:

    您可以使用str strip() 方法删除行尾的空格和换行符。

    所以,大概是这样的:

    words = list()
    
    with open("my_file_path") as file:
        for line in file:
            words.append(line.strip())
    
    result = " ".join(words)
    

    使用生成器表达式:

    with open("my_file_path") as file:
        result = " ".join(line.strip() for line in file)
    

    【讨论】:

    • 它有效,但@AlexanderCécile 解决方案更好:)
    • @Eraw awn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多