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

时间:2014-11-26 05:02:46

标签: python processing

我正在使用读取txt文件的处理创建程序并将结果发送到arduino。 我可以让它发送字符串并保持更新,但是一旦我尝试发送最后一个字符它就无法工作......任何人都可以帮我这个吗?基本上我需要读取txt文件中的最后一个字符并将其作为char通过串口发送到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
  • 此文件将以此格式持续更新

5 个答案:

答案 0 :(得分:7)

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

with open(filename, 'rb+') as f:
    f.seek(-1,2)
    print f.read()

Seek是一个处理评论的文件对象

<强> file.seek(偏移,位置)

  1. 偏移:你需要多少个字符。(即)1表示一个字符
  2. postion :告诉你的文件读/写操作应该从哪里开始
    1. 0表示启动文件
    2. 1表示文件读/写光标的当前位置
    3. 2表示文件结束
  3. f.seek(-1,2)表示转到文件末尾并遍历一个元素

    print f.read()打印从搜索命令

    获取的值

答案 1 :(得分:2)

Stefan的答案很简单,很有效,但不考虑以下文本文件:

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

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

以下是解决这两个问题的例子。

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编码文件。

答案 2 :(得分:1)

我做了什么:

  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:]
    
  4. 希望有所帮助

答案 3 :(得分:0)

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

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

步骤进行:

  1. 打开文件
  2. 将其转换为列表
  3. 将列表加入str form
  4. 得到了最后一个角色!
  5. 现在,如果想要以int形式使用该角色,只需:

    pos=int(s[-1:])
    

答案 4 :(得分: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”来读取文件非常重要