user12037376
user12037376

Reputation:

Read only 4 first letters of .txt file - Python3

I'm trying to read only the 4 letters of a .txt file in my python tool and then set a variable with that 4 letters. In that .txt I export the device arch with adb with subprocess for detect if the connected device has an mtk 64 bit based platform. My idea, as said before, is read only the first 4 letters of the txt, for example, I connect a device with mt6735 and the tool reads that platform in the .txt. Then I only need to read the 4 letters for see if the platform starts with mt67 or mt81. Is that possible?

I've tried with seek:

with open('platform.txt') as myfile:
  myfile.seek(2,1)
    platform = myfile.read()

But I get this error:

Traceback (most recent call last):
  File "mtk-su_linux.py", line 40, in <module>
    myfile.seek(2,1)
io.UnsupportedOperation: can't do nonzero cur-relative seeks

What is the correct way for do this?

Thanks in advance!

And best regards.

Upvotes: 0

Views: 698

Answers (2)

jojo
jojo

Reputation: 279

Is filename a variable representing the file? Or is the file 'platform.txt'? I think what you want is:

with open('platform.txt', 'r') as myfile:
    platform = myfile.read(4)

OR if you want to open both 'platform.txt' and filename where filename = 'some_file.txt', if you're trying to read the platforms from a bunch of files and you want to record them in the file 'planform.txt', you could use:

with open(filename, 'r') as myfile, open('platform.txt', 'a') as record:
    platform = myfile.read(4)
    record.write(platform)

The arguments 'r' and 'a' stand for read and append respectively--specifying how the file is going to be used. 'w' for write is also commonly used, but it will start with the cursor at the beginning of the document, so anything you write will overwrite anything already in the doc.

Upvotes: 2

Ezphares
Ezphares

Reputation: 359

As per the python input and output documentation, read() accepts a maximum number of characters to read, so you can use

platform = myfile.read(4)

Upvotes: 0

Related Questions