How to find byte at specific index from file? - python

I need to print byte at specific position in file that i know path. So I open default file in "rb" mode and then I need to know what byte is on 15 position. It is posible ?

Here's how you can achieve this with seek:
with open('my_file', 'rb') as f:
f.seek(15)
f.read(1)

Another way you could do this is to read the entire document and slice it:
First read the contense of the file:
file = open('test.txt', 'rb')
a = file.read()
Then take the desired value:
b = a[14]
Then don't forget to close the file afterwards:
file.close()
Or so that is closes automatically:
with open('test.txt', 'rb') as file:
a = file.read()
b = a[14]

Related

How to write an array to a file and then call that file and add more to the array?

So as the title suggests I'm trying to write an array to a file, but then I need to recall that array and append more to it and then write it back to the same file, and then this same process over and over again.
The code I'm have so far is:
c = open(r"board.txt", "r")
current_position = []
if filesize > 4:
current_position = [c.read()]
print(current_position)
stockfish.set_position(current_position)
else:
stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
#There is a lot more code here that appends stuff to the array but I don't want to #add anything that will be irrelevant to the problem
with open('board.txt', 'w') as filehandle:
for listitem in current_position:
filehandle.write('"%s", ' % listitem)
z = open(r"board.txt", "r")
print(z.read())
My array end up looking like this when I read the file
""d2d4", "d7d5", ", "a2a4", "e2e4",
All my code is on this replit if anyone needs more info
A few ways to do this:
First, use newline as a delimiter (simple, not the most space efficient):
# write
my_array = ['d2d4', 'd7d5']
with open('board.txt', 'w+') as f:
f.writelines([i + '\n' for i in my_array])
# read
with open('board.txt') as f:
my_array = f.read().splitlines()
If your character strings all have the same length, you don't need a delimiter:
# write
my_array = ['d2d4', 'd7d5'] # must all be length 4 strs
with open('board.txt', 'w+') as f:
f.writelines(my_array)
# read file, splitting string into groups of 4 characters
with open('board.txt') as f:
in_str = f.read()
my_array = [in_str[i:i+4] for i in range(0, len(in_str), 4)]
Finally, consider pickle, which allows writing/reading Python objects to/from binary files:
import pickle
# write
my_array = ['d2d4', 'd7d5']
with open('board.board', 'wb+') as f: # custom file extension, can be anything
pickle.dump(my_array, f)
# read
with open('board.board', 'rb') as f:
my_array = pickle.load(f)
as you're reusing the file to append data to it, you should replace:
open('board.txt', 'w')
with
open('board.txt', 'a')
a denotes append mode. Which will not overwrite what you have in your file, it will append to it.

reading .txt file in python

I have a problem with a code in python. I want to read a .txt file. I use the code:
f = open('test.txt', 'r') # We need to re-open the file
data = f.read()
print(data)
I would like to read ONLY the first line from this .txt file. I use
f = open('test.txt', 'r') # We need to re-open the file
data = f.readline(1)
print(data)
But I am seeing that in screen only the first letter of the line is showing.
Could you help me in order to read all the letters of the line ? (I mean to read whole the line of the .txt file)
with open("file.txt") as f:
print(f.readline())
This will open the file using with context block (which will close the file automatically when we are done with it), and read the first line, this will be the same as:
f = open(“file.txt”)
print(f.readline())
f.close()
Your attempt with f.readline(1) won’t work because it the argument is meant for how many characters to print in the file, therefore it will only print the first character.
Second method:
with open("file.txt") as f:
print(f.readlines()[0])
Or you could also do the above which will get a list of lines and print only the first line.
To read the fifth line, use
with open("file.txt") as f:
print(f.readlines()[4])
Or:
with open("file.txt") as f:
lines = []
lines += f.readline()
lines += f.readline()
lines += f.readline()
lines += f.readline()
lines += f.readline()
print(lines[-1])
The -1 represents the last item of the list
Learn more:
with statement
files in python
readline method
Your first try is almost there, you should have done the following:
f = open('my_file.txt', 'r')
line = f.readline()
print(line)
f.close()
A safer approach to read file is:
with open('my_file.txt', 'r') as f:
print(f.readline())
Both ways will print only the first line.
Your error was that you passed 1 to readline which means you want to read size of 1, which is only a single character. please refer to https://www.w3schools.com/python/ref_file_readline.asp
I tried this and it works, after your suggestions:
f = open('test.txt', 'r')
data = f.readlines()[1]
print(data)
Use with open(...) instead:
with open("test.txt") as file:
line = file.readline()
print(line)
Keep f.readline() without parameters.
It will return you first line as a string and move cursor to second line.
Next time you use f.readline() it will return second line and move cursor to the next, etc...

How to read last string in a file

I have a file.txt which is saving as list
['Joe', '101', '/home/Joe', '43242', '/home/Joe/1.txt']
How to read the last element in the file here it is '/home/Joe/1.txt'
I tried to read
with open ('file.txt', r) as fr:
fd = fr.readlines()
print (fd[-1])
You could use ast.literal_eval()
from ast import literal_eval
with open("test.txt") as fp:
content = fp.read()
lst = literal_eval(content)
print(lst[-1])
# /home/Joe/1.txt
As said in the commentary, better use other structures to store your information, e.g. pickle, json, etc.
Please change t to 'rt' when reading from a file in python:
with open ('file.txt', 'rt') as fr:
fd = fr.readlines()
print (fd[-1])
Note: it is 'rt' instead of t.
Try to,
with open('file.txt') as fr:
fd = fr.readlines()[0].split(',')[-1].strip(']')
print(fd)
#'/home/Joe/1.txt'

Cannot save string to file with `\n` characters

The following code produces a file with content test\\nstring, but I need the file to contain test\nstring. I can't figure out a way to replace the \\symbol either.
s = "test\nstring"
with open('test.txt', 'w') as f:
f.write(s)
How can I make sure that the file contains only \n instead of \\n?
use s = "test\\nstring"
I tried with the following code and worked.
s = "test\\nstring"
with open('test.txt', 'w') as f:
f.write(s)
and the test.txt file contains
test\nstring
Besides of escaping and raw string, you can encode it (2 or 3) with 'string_escape':
s = "test\nstring".encode('string_escape')
with open('test.txt', 'w') as f:
f.write(s)
The raw strings may help
s = r"test\nstring"
with open('test.txt', 'w') as f:
f.write(s)

python read value from file and change it and write back to file

i am reading a value from a file and then adding up with another and then writing back to the same file.
total = 0
initial = 10
with open('file.txt', 'rb') as inp, open('file.txt', 'wb') as outp:
content = inp.read()
try:
total = int(content) + int(initial)
outp.write(str(total))
except ValueError:
print('{} is not a number!'.format(content))
it is successfully reading the value from file, but when writing, nothing is stored in the file.
what is wrong here?
update
I want to replace the old value, not append to it. Erase the old value and then put the new value instead.
you can't open your file twice simultaneously,
your code should look like this:
total = 0
initial = 10
with open('file.txt', 'rb') as inp:
content = inp.read()
total = int(content) + int(initial)
with open('file.txt', 'wb') as outp:
outp.write(str(total))
A look at this could help you:
Beginner Python: Reading and writing to the same file
I do not know which Python version you use, but both 2.7.13 and 3.6.1 versions give me the following error: b'' is not a number!. So because an error is raised, the write instruction is not interpreted.
The with statement is evaluated from left to right. So first, your file is open in read mode. Right after that, it is open in write mode and that causes the file to be truncated: there is nothing more to read.
You should proceed in two steps:
total = 0
initial = 10
# First, read the file and try to convert its content to an integer
with open('file.txt', 'r') as inp:
content = inp.read()
try:
total = int(content) + int(initial)
except ValueError:
print('Cannot convert {} to an int'.format(content))
with open('file.txt', 'w') as outp:
outp.write(str(total))

Categories

Resources