如何在python中一次从文件中读取x个字符?
myfile.txt包含“生存还是毁灭,这是个问题” 我试图编写程序,在换行符上一次输出x个字符,这样x=8的输入将是:如何在python中一次从文件中读取x个字符?,python,Python,myfile.txt包含“生存还是毁灭,这是个问题” 我试图编写程序,在换行符上一次输出x个字符,这样x=8的输入将是: to be or not to be that is the q uestion 我不知道如何让我的代码每次继续打印换行符上的下8个字符 def read_file(): x = int(input("How many letters do you want to read each time : ")) # number of characters to rea
to be or
not to
be that
is the q
uestion
我不知道如何让我的代码每次继续打印换行符上的下8个字符
def read_file():
x = int(input("How many letters do you want to read each time : ")) # number of characters to read on each newline
f = open('myfile.txt')
contents = f.read(x)
print(contents) # only prints first 8 characters
read_file()
您需要围绕阅读/打印部分进行循环:
def read_file():
x = int(input("How many letters do you want to read each time : ")) # number of characters to read on each newline
f = open('myfile.txt')
while True:
contents = f.read(x)
if not contents:
break
print(contents)
您需要通过循环读取它:
contents = []
while True:
chunk = f.read(x)
if not chunk:
break
contents.append(chunk)
print(contents)
您可以使用“切片”来获取字符串的部分。检查全面的介绍。
我找到的解决办法是:
def read_file():
x = int(input("How many letters do you want to read each time : "))
f = open('myfile.txt')
contents = f.read()
temp = x
temp_string = contents
while(len(contents) >= temp):
print(temp_string[:x])
temp_string = contents[x:]
contents = temp_string
print(temp_string[:x])# this need for last part
read_file()
请注意,这行代码可以使文件保持打开状态以供读取。尝试使用
with
语句
f = open('myfile.txt')
参考:
其他答案没有错。我想在Python3.8中添加一个带有最近引入的赋值表达式“walrus操作符”的解决方案
参考:
输出:
to be or
not to
be that
is the q
uestion
示例#1
示例2
您只需调用
read
一次,因此您当然只会得到前八个字符。您需要多次调用read
,直到完成。你考虑过某种循环吗?
to be or
not to
be that
is the q
uestion
# -*- coding: utf-8 -*-
def read_n_datas(x_characters,
file_path,
my_mode='r',
my_encoding=None):
with open(file_path, mode=my_mode, encoding=my_encoding) as f:
assert isinstance(x_characters, int) and x_characters
r = f.read(x_characters)
while r:
y = yield r
r = f.read(y or x_characters)
x = int(input("How many letters do you want to read each time : ")) # number of characters to read on each newline
e = read_n_datas(x, 'myfile.txt')#read 'x' on first call or as default
next(e)#init the generator
print(e.send(3))#read 3 more characters
print(e.send(10))#read 10 more characters
print(e.send(5))#read 5 more characters
x = int(input("How many letters do you want to read each time : ")) # number of characters to read on each newline
e = read_n_datas(x, 'myfile.txt')#read 'x' on first call or as default
for t in e:
print(t)