[英]How to get the last character in a file from Python?
我正在尝试将变量设置为文件的最后一个字符。 我正在使用 Python,我对它还很陌生。 如果它很重要,我的代码会在 HTML 文件的末尾附加一个 2 到 9 之间的随机数。 在单独的 function 中,我想将 HTML 文件的最后一个字符(最后一个字符是 2 到 9 之间的随机数)设置为一个变量,然后删除最后一个字符(以免影响 HTML 的 ZC1C425268E683845F1AB450)。 有谁知道我怎么能做到这一点? 如果需要,我可以在下面附上我的代码,但我选择不这样做,因为它有 50 行长,并且完整的上下文需要所有 50 行。
尝试这个,
“a.txt”文件的编号为1, 3, 4, 5
下面的代码将读取文件并从文件中提取最后一个字符。
file = open('a.txt','r')
lines = file.read()
print(lines[-1])
=> 5
你可以这样做:
# 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)
如果您不想创建新文件,您可以像我们目前正在做的那样将所有文件加载到 memory:
# 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)
使用上面评论中@Jab 的回答以及一些假设,我们可以产生一个更有效的解决方案来查找最后一个字符并替换它。
所做的假设很常见并且很可能是有效的:
所以,这就是我们可以做的:
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()
这是有效的,因为我们实际上不必遍历整个文件。 我们只遍历最后一个字符,一次读取一次写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.