[英]I don't understand why i can't get readline function in python to work in this program. What am I doing wrong?
In this program I want to save individual lines to a variable but when i try to print the variable it just returns a space instead of whats on the line in the file.在这个程序中,我想将单独的行保存到一个变量中,但是当我尝试打印该变量时,它只返回一个空格,而不是文件中行上的内容。 sorry i'm quite new to programming抱歉,我对编程很陌生
file=open('emails.txt','w+')
while True:
email=input('pls input your email adress: ')
file.write(email)
file.write('\n')
more=input('would you like more emails to be processed? ')
if more == 'yes' or more == 'ye' or more == 'y' or more == 'yep' or more == 'Y':
continue
elif more == 'no' or more == 'nah' or more == 'n' or more == 'N' or more == 'nope':
file.close()
print('this is the list of emails so far')
file=open('emails.txt','r')
print(file.read()) #this reads the whole file and it works
email_1=file.readline(1) #this is meant to save the 1st line to a variable but doesn't work!!!
print(email_1) #this is meant to print it but just returns a space
file.close()
print('end of program')
First, you should use with
to work with files.首先,您应该使用with
来处理文件。
Second, you open the file for printing and read all of its content: print(file.read())
其次,您打开文件进行打印并读取其所有内容: print(file.read())
after this line, the cursor is in the end of the file, so next time you try to read something from the file, you get empty string.在这一行之后,cursor 位于文件末尾,因此下次尝试从文件中读取内容时,会得到空字符串。
to fix it, you have few alternatives.要修复它,您几乎没有其他选择。
First option:第一个选项:
add file.seek(0, 0)
to move the cursor back to the start of the file so when you do file.readline
, you will realy read the file line.添加file.seek(0, 0)
将 cursor 移回文件的开头,因此当您执行file.readline
时,您将真正读取文件行。
moreover, file.readline(1)
should be changed to file.readline()
此外, file.readline(1)
应改为file.readline()
Second option:第二种选择:
just read all the file content into a list, print it and then print the first entry in the list(the first line in the file...)只需将所有文件内容读入列表,打印它然后打印列表中的第一个条目(文件中的第一行......)
file = open('emails.txt', 'r')
content = file.readlines()
print(*content, sep='')
email_1 = content[0]
print(email_1)
As mentioned in the first comment above, the file.read() call is moving your file pointer to the end of the file, so there is no data left for the readline() to read.正如上面第一条评论中提到的,file.read() 调用将文件指针移动到文件末尾,因此没有数据可供 readline() 读取。
But also, you are calling readline(1) which will read one byte, not one line.而且,您正在调用 readline(1) 它将读取一个字节,而不是一行。
Well I would try to use with
好吧,我会尝试with
So try to implement it like this:所以尝试像这样实现它:
> with open('emails.txt','w+') as output_file:
while True:
# and then rest of your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.