仅读取.txt 文件中的最后一个字符

问题描述 投票:0回答:6

我正在创建一个使用处理读取txt文件并将结果发送到arduino的程序。 我可以让它发送字符串并保持更新,但是一旦我尝试发送最后一个字符,它就不起作用......任何人都可以帮助我吗?基本上我需要从 txt 文件中读取最后一个字符,并将其作为字符通过串行发送到 arduino、python 或处理两者都可以!

*这是我的代码[正在处理]

import processing.serial.*;
import java.io.*;

int mySwitch=0;
int counter=0;
String [] subtext;
Serial myPort;
   
void setup(){
   //Create a switch that will control the frequency of text file reads.
   //When mySwitch=1, the program is setup to read the text file.
   //This is turned off when mySwitch = 0
   mySwitch=1;
 
   //Open the serial port for communication with the Arduino
   //Make sure the COM port is correct
   myPort = new Serial(this, "COM4", 9600);
   myPort.bufferUntil('\n');
}

void draw() {
   if (mySwitch>0){
       /*The readData function can be found later in the code. This is the call to read a CSV file on the computer hard-drive. */
       readData("G:/Personal/control.txt");
 
       /*The following switch prevents continuous reading of the text file, until   we are ready to read the file again. */
       mySwitch=0;
   }

   /*Only send new data. This IF statement will allow new data to be sent to the arduino. */
   if(counter<subtext.length){
       /* Write the next number to the Serial port and send it to the Arduino There will be a delay of half a second before the command is sent to turn the LED off : myPort.write('0'); */
       myPort.write(subtext[counter]);
       delay(500);
       myPort.write('0');
       delay(100);

       //Increment the counter so that the next number is sent to the arduino.
       counter++;
   } else{
       //If the text file has run out of numbers, then read the text file again in 5 seconds.
       delay(5000);
       mySwitch=1;
   }
} 


/* The following function will read from a CSV or TXT file */
void readData(String myFileName){
 
 File file=new File(myFileName);
 BufferedReader br=null;
 
 try{
   br=new BufferedReader(new FileReader(file));
   String text=null;
 
   /* keep reading each line until you get to the end of the file */
 while((text=br.readLine())!=null){
   * Spilt each line up into bits and pieces using a comma as a separator */

   subtext = splitTokens(text,",");
 }
 }catch(FileNotFoundException e){
     e.printStackTrace();
 }catch(IOException e){
     e.printStackTrace();
 }finally{
     try {
        if (br != null){
           br.close();
        }
     } catch (IOException e) {
     e.printStackTrace();
   }
 }

这是我正在处理的数据

[19:54:57] [服务器线程/信息]:[@] b

[19:54:57] [服务器线程/信息]:[@] a

[19:54:57] [服务器线程/信息]:[@] b

[19:54:57] [服务器线程/信息]:[@] a

[19:54:58] [服务器线程/信息]:[@] b

[19:54:58] [服务器线程/信息]:[@] a

[19:54:59] [服务器线程/信息]:[@] b

[20:30:23] [服务器线程/信息]:[@] a

[20:30:24] [服务器线程/信息]:[@] b

[21:07:34] [服务器线程/信息]:[@] a

[21:07:35] [服务器线程/信息]:[@] b

  • 我真正关心的唯一值是 a / b
  • 并且此文件将以这种格式持续更新
python processing
6个回答
12
投票

从文件中读取最后一个字符:

with open(filename, 'rb+') as f:
    f.seek(f.tell()-1,2)    # f.seek(0,2) is legal for last char in both python 2 and 3 though
    print f.read()

对于Python 3
为了使其更通用,我们想在不打开二进制模式的情况下读取文件的倒数第二个(可以是任意)字符:

with open('file.txt', 'r') as f:
    f.seek(0, 2)
    # seek to end of file; f.seek(0, os.SEEK_END) is legal

    f.seek(f.tell() - 2, 0)
    # seek to the second last char of file;
    # while f.seek(f.tell()-2, os.SEEK_SET) is legal,
    # f.seek(-2, 0) will throw an error.

    print(f.read())

Seek 是处理注释的文件对象

file.seek(offset,position)

  1. offset
    :您需要多少个字符(即1表示一个字符)
  2. position
    :告诉你的文件读/写操作应该从哪里开始。
    • 0 表示文件开始
    • 1 表示文件读/写光标当前位置
    • 2 表示文件结束

f.seek(f.tell()-1,2)
表示转到文件末尾并回溯一个元素

print f.read()
打印从seek命令获得的值


6
投票

Stefan 的回答很简单,也很有效,但没有考虑文本文件:

  • UTF-8 编码 包含非英文字符(这是 Python 3 中文本文件的默认编码)
  • 文件末尾有一个 换行符(这是 Linux 编辑器中的默认设置,如
    vim
    gedit

如果文本文件包含非英语字符,则到目前为止提供的答案都不起作用。

下面的示例可以解决这两个问题。

import os


def get_last_utf8_char(filename, ignore_newlines=True):
    """
    Reads the last character of a UTF-8 text file.
    :param filename: The path to the text file to read
    :param ignore_newlines: Set to true, if the newline character at the end of the file should be ignored 
    :return: Returns the last UTF-8 character in the file or None, if the file is empty 
    """
    with open(filename, 'rb') as f:
        last_char = None

        # Reads last 4 bytes, as the maximum size of an UTF-8 character is 4 bytes
        num_bytes_to_read = 4

        # If ignore_newlines is True, read two more bytes, as a newline character
        # can be up to 2 bytes (eg. \r\n)
        # and we might have a newline character at the end of file
        # or size bytes, if file's size is less than 4 bytes
        if ignore_newlines:
            num_bytes_to_read += 2

        size = os.fstat(f.fileno()).st_size
        f.seek(-min(num_bytes_to_read, size), os.SEEK_END)
        last_bytes = f.read()

        # Find the first byte of a UTF-8 character, starting
        # from the last byte
        offset = -1
        while abs(offset) <= len(last_bytes):
            b = last_bytes[offset]
            if ignore_newlines and b in b'\r\n':
                offset -= 1
                continue
            if b & 0b10000000 == 0 or b & 0b11000000 == 0b11000000:
                # If this is first byte of a UTF8 character,
                # interpret this and all bytes after it as UTF-8
                last_char = last_bytes[offset:].decode('utf-8')
                break
            offset -= 1

        if last_char and ignore_newlines:
            last_char = last_char.replace('\r', '').replace('\n', '')

        return last_char

工作原理:

  • 以二进制模式仅读取 UTF-8 编码文本文件的最后几个字节
  • 向后迭代字节,寻找 UTF-8 字符的开头
  • 一旦找到字符(不同于换行符),将其作为文本文件中的最后一个字符返回

示例文本文件 -

bg.txt
:

Здравей свят

使用方法:

>>> get_last_utf8_char('bg.txt')
т

这适用于 UTF-8 和 ASCII 编码文件。


0
投票

我做了什么:

  1. 打开文件。
  2. 将最后一行作为列表读取。
  3. 将其转换为字符串并读取最后一个字符并打印出来。

    a=open('does&donts.txt','rb')
    lines = a.readlines()
    a.close()
    if lines:
        last_line = lines[-1]
    print  last_line
    b="".join(last_line)
    print b[-1:]
    

希望有帮助


0
投票

只需使用这个:

with open("file.txt", "r") as f:
    file_str = str(f.read())
    f.close()
last_chr = file_str[-1]
print(last_chr)

通过“r”而不是“rb”读取文件很重要


0
投票

我注意到最后一个字符的字节值始终为 255,即使 ASCII 值的范围是从 0 到 127。当我编写一个小程序来区分 ASCII 和二进制文件时,我一开始发现这很麻烦,但这可能是一个更轻松地从硬盘恢复数据的约定。


-1
投票

我能想到的最简单的事情:

s="".join(list(open(rfile_directory))) 
pos=s[-1:]

步骤:

  1. 打开文件
  2. 将其转换为列表
  3. 以str形式加入列表
  4. 获得最后一个角色!

现在,如果需要 int 形式的字符,只需:

pos=int(s[-1:])
© www.soinside.com 2019 - 2024. All rights reserved.