Py学习  »  Python

将变量值添加到。txt文件和读取。指定给变量的txt特定行(python)

Daniel • 3 年前 • 1247 次点击  

因此,我目前正在学习代码,我目前正在做一些小型/初学者项目,以熟悉python语言。

通常我可以通过寻找我想要的东西。。。

但这次我被卡住了。

我想做的对你们大多数人来说非常简单。。。 我想开一家店。txt文件(文件创建代码已准备就绪)读取文件的特定行。txt并将其分配给一个变量,该变量稍后用于与另一个用户输入变量进行比较。。。

抱歉,如果不是很清楚。

所以这就是我要说的。。。

with open('infos.txt', 'r') as f:
    lines = f.readlines()

user_master = lines[0]
print(user_master) # this gives the output that i want: "test"

if user_master == "test":
    print("OK") # This does not work, no output on the console... 
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129440
 
1247 次点击  
文章 [ 2 ]  |  最新文章 3 年前
martineau
Reply   •   1 楼
martineau    3 年前

问题在于列表中的每一行都是从 readlines() 有一个尾随的新行,所以 if user_master == "test" 失败。最简单的修复方法是利用内置的 str,splitlines() 方法:

with open('infos.txt', 'r') as f:
    lines = f.read().splitlines()  # Create list of lines with newlines stripped.

user_master = lines[0]
print(user_master) # -> test

if user_master == "test":
    print("OK") # This now works.
Pedro Maia
Reply   •   2 楼
Pedro Maia    3 年前

你可以用 .readlines() 要获取所有行并通过索引获取所需行,请执行以下操作:

with open('myfile.txt', 'r') as f:
    lines = f.readlines()

line = lines[INDEX].strip()