代码之家  ›  专栏  ›  技术社区  ›  Muhsin Muhammed

向文件中的行添加引号和逗号

  •  0
  • Muhsin Muhammed  · 技术社区  · 3 年前

    我试图从一个文件中读取如下字符串:

    123456
    password
    12345678
    qwerty
    123456789
    12345
    1234
    111111
    1234567
    dragon
    ...till the end
    

    我想把每一行打印到一个文件中,用下面的方式插入引号和逗号,

    "123456",
    "password",
    "12345678",
    ...till the end
    

    我试过:

    fhand = open("pass.txt")
    
    for line in fhand:
        print(f'"{line}",',end="")
    

    但是,这段代码在错误的位置打印引号和逗号:

    "123456
    ","password
    ","12345678
    ","qwerty
    ...till the end
    

    我怎样才能消除这些虚假的新词呢?

    1 回复  |  直到 3 年前
        1
  •  2
  •   BrokenBenchmark Miles Budnek    3 年前

    两件事:

    1. 第一次读入时,每行包含一个尾随换行符。使用:

      line.rstrip()
      

      而不是 line 在格式字符串中。

    2. 与您询问的问题无关,但值得指出的是:您应该使用 fhand.close() 之后 for 环更好的方法是使用上下文管理器,它会自动关闭文件句柄:

      with open("pass.txt") as fhand:
          for line in fhand:
              print(f'"{line.rstrip()}",',end="")