【问题标题】:Python based on .txt file基于 .txt 文件的 Python
【发布时间】:2020-03-30 16:02:33
【问题描述】:

我拥有一个包含多行的 txt 文件每一行将作为下一行

email1:password1
email2:password2
...
...
...
emailxx:passwordxx

我想要一个 python 代码一次读取文件行,在哪里打印下一个

email=username1
pass=password1

email=username2
pass=password2

email=username3
pass=password3
...
...
...
email=usernamexx
pass=passwordxx

【问题讨论】:

  • usernamexx 来自哪里?并且密码是否始终是用户的密码和 id(我猜是 ID)?

标签: python linux txtextcontrol


【解决方案1】:

尝试以下方法:

with open('path/to/file.txt','r') as f:
    values = f.readline().split(":")
    print(f"email={values[0]}")
    print(f"pass={values[1]}\n")

【讨论】:

  • Traceback(最近一次调用最后一次):文件“ss.py”,第 3 行,在 f.write(f"email={values[0]}\n") io。 UnsupportedOperation:不可写
【解决方案2】:

谢谢我修好了

with open("xxx.txt") as f:
for line  in f.readlines():
   #print(line)
   values = line.split(":")
   email = values[0]
   pasw = values[1]
   print(f"user={email}\npass={pasw}\n")

【讨论】:

  • 使用open()时不需要close()
【解决方案3】:

open 函数为您提供一个文件对象,并具有从文件中读取行的方法。

with open(filepath) as f:
    for line  in f.readlines():
       print(line)
       info = line.strip(":"))
       output = f"email={info[0]}\npass={info[2]}"
       print(output) 
f.close() #Close the file when you're done.

【讨论】:

  • 使用open() 你不需要close()。另外,为什么要readlines()可以readline()
  • readlines 只进行一次操作,而不是单独询问每一行。
猜你喜欢
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
相关资源
最近更新 更多