【问题标题】:How to get the last character in a file from Python?如何从 Python 获取文件中的最后一个字符?
【发布时间】:2021-06-02 19:37:38
【问题描述】:

我正在尝试将变量设置为文件的最后一个字符。我正在使用 Python,而且我对它还很陌生。如果它很重要,我的代码会在 HTML 文件的末尾附加一个 2 到 9 之间的随机数。在一个单独的函数中,我想将 HTML 文件的最后一个字符(最后一个字符是 2 到 9 之间的随机数)设置为一个变量,然后删除最后一个字符(以免影响 HTML 的功能)。有谁知道我怎么能做到这一点?如果需要,我可以在下面附上我的代码,但我选择不这样做,因为它有 50 行长,并且完整的上下文需要所有 50 行。

【问题讨论】:

  • 是设置最后一个还是获取最后一个?
  • “我的代码太长,无法分享”:这就是我们要求minimal reproducible example的原因!
  • @enzo 我想从 HTML 文件中获取最后一个字符,定义一个变量为“var = lastChar”,然后删除 HTML 文件的最后一个字符。
  • @PranavHosangadi 正如我的问题所述,完整的问题上下文需要所有 50 行。我可以将代码简化为代表函数的 cmets,但我觉得这会导致进一步的混乱。
  • 这能回答你的问题吗? Only read the last character in a .txt file

标签: python


【解决方案1】:

试试这个,

“a.txt”文件编号为1, 3, 4, 5

以下代码将读取文件并从文件中提取最后一个字符。

file = open('a.txt','r')  
lines = file.read()       
print(lines[-1])    

=> 5

【讨论】:

  • 这不会返回“a.txt”的整个最后一行吗?
  • @TBQTLS 没有。 lines 名称错误。它实际上是整个文件字符串
  • @ch2019 这解决了我的问题,但此代码不会删除最后一个字符。我会将其标记为已回答。感谢您的帮助。
  • @TBQTLS 如果这段代码没有完全解决你的问题,你为什么接受它?
  • 文件打开阅读后不应该关闭吗?
【解决方案2】:

你可以这样做:

# Open the file to read and the file to write
with open('file.txt'), open('new_file.txt', 'w+') as f_in, f_out:
    # Read all the lines to memory (you can't find the last line lazily)
    lines = f_in.readlines()

    # Iterate over every line
    for i, line in enumerate(lines):
        # If the current index is the last index (i.e. the last line)
        if i == len(lines) - 1:
            # Get the last character
            last_char = line[-1]

            # Write to the output file the line without the last character
            print(line[:-1], file=f_out, end='')

        else:
            # Write to the output file the line as it is
            print(line, file=f_out, end='')

# Print the removed char
print(last_char)    

如果您不想创建新文件,您可以像我们目前所做的那样将所有文件加载到内存中:

# Read all the lines into memory
with open('file.txt') as f:
    lines = f.readlines()

# Replace the lines inside the list using the previous logic
for i, line in enumerate(lines):
    if i == len(lines) - 1:
       last_char = line[-1]
       lines[i] = line[:-1]

    else:
       lines[i] = line

# Write the changed lines to the same file
with open('file.txt', 'w+') as f:
    print(''.join(lines), file=f, end='')

# Print the removed char
print(last_char)    

【讨论】:

    【解决方案3】:

    使用上面评论中@Jab 的回答以及一些假设,我们可以产生一个更有效的解决方案来查找最后一个字符并替换它。

    所做的假设很常见并且很可能是有效的:

    1. 您将知道文件末尾是否有换行符,或者随机数是否真的是文件中的最后一个字符(意味着考虑空格)。
    2. 您知道文件的编码。这是有效的,因为几乎所有的 HTML 都是 utf-8,(可以是 utf-16),而且你是编辑它的人,你会知道的。大多数情况下,编码甚至都无关紧要。

    所以,我们可以这样做:

    with open("test.txt", "rb+", encoding='utf-8') as f:
        f.seek(-2, 2)
        # -1 or -2, may change depending on whitespace characters at end of the file
        var = f.read(1) # read one byte for a number 
        f.seek(-1,1)
        print("last character:", str(var, 'utf-8'))
        f.write(bytes('variable', 'utf-8')) # set whatever info here
        f.write(bytes('\n', 'utf-8')) # you may want a newline character at the end of the file
        f.truncate()
    

    这很有效,因为我们实际上不必遍历整个文件。我们只遍历最后一个字符,一次读取一次写入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 2011-07-07
      • 2011-08-17
      • 2019-04-16
      相关资源
      最近更新 更多