如何将 .txt 文件的前 30 个字符添加到变量?

How to add first 30 chars of a .txt file to a variable?

所以我有这个作业问题:

school_prompt.txt的前30个字符作为字符串分配给变量beginning_chars.

在上一个问题中,我设法计算了 txt 文件中的所有字符,但我不知道如何将前 30 个添加到变量中。

fname = "school_prompt.txt"
lines = 0
nwords = 0
beginning_chars = 0 
with open(fname, 'r') as f:
    for line in f:
        if line >= 30:
            words = line.split()
            lines +=1 
            nwords += len(words)
            beginning_chars += len(line)

就这么简单:

fname = "school_prompt.txt"
with open(fname, 'r') as f:
    beginning_chars = f.read(30)

read方法可以将要读取的字节数作为参数。在大多数编码中,一个字节等于一个字符。