unable to read the data from file in python - python

I am unable to read the data from file in python . Below is the sample code and Error which I am getting .
abc.txt has the value 2015-05-07
f = open("/opt/test/abc.txt","r")
f.read()
last_Exe_date = f.read()
f.close()
while reading the file(anc.txt) i am getting the error : TypeError: argument 1 must be string or read-only character buffer, not file . i am not able to read the value into last_Exe_date from file(abc.txt) . could you please correct me if I am wrong with the code.

When you read a file once, the cursor is at the end of the file and you won't get anything more by re-reading it. Read through the docs to understand it more. And use readline to read a file line by line.
Oh, and remove the semicolon at the end of your read calls...

The following should work fine:
f = open("/opt/test/abc.txt","r")
last_Exe_date = f.read()
f.close()
As was said, you had f.read() twice, so when you tried to store the contents into last_Exe_date, it would be empty.
You could also consider using the following method:
with open("/opt/test/abc.txt","r") as f:
last_Exe_date = f.read()
This will ensure that the file is automatically closed afterwards.

Related

How can I store an output print data?

My script prints top 5 subreddits from specified redditor.
reddit = praw.Reddit(
client_id="",
client_secret="",
password="",
user_agent="",
username="",
)
for submission in reddit.redditor("").top(limit=5):
print(submission.subreddit)
Im trying to store in txt file what is being printed.
I was trying to use this method:
f = open('file.txt', 'w+')
f.write(submission.subreddit)
f.close()
But received this error at the end
TypeError: write() argument must be str, not Subreddit
Any ideas how can I store subreddits in txt file?
When you are writing something to a file, but the something is not a string, you need to first convert it to a string.
str_subreddit = str(submission.subreddit)
However, there are better ways of doing what you're trying to do:
Use Unix shell to redirect output of your program to a file: python my_script.py > file.txt
To append instead of overwriting, use >>
This is arguably a better method, because it follows the Unix philosophy
print takes a file argument: print(str_subreddit, file=f)
You will of course have to open the file at the beginning of your program
Also, if you are trying to append to a file with f = open('file.txt', 'w+'), you want a not w+. w+ is something else.

Write list of bytes into a file, but some records got lost

I am new to programming and got an issue with writing bytes. Here is what I wrote:
file = open('filePath/input.train', 'wb')
for i in range(len(myList)):
file.write(bytes((myList[i]),'UTF-8'));
If I print 'i' here, it is 629.
The '.train' suffix is required by the project. In order to check it, I read it and write to a txt file:
file = open('filePath/input.train', 'rb')
content = file.read()
testFile = open('filePath/test.txt', 'wb')
testFile.write(content)
Now, the problem is, len(list) = 629 while I got 591 lines in test.txt file. It brought me problems later.
Why did this happen and how should I solve it?
first, when you open and write a file, need remember close the file after the write.like this.
file = open('filePath/input.train', 'wb')
for i in range(len(myList)):
file.write(bytes((myList[i]),'UTF-8'));
file.close()
second, python code not must has ";"
third, file is python's keyword, so don't use file be your variable name. you can use f or my_file or anyone, but don't use python's keyword.
fourth, python has a iterator, use iterator is better than your for i in range(len(xxx)).
all of this, your code can look like this.
f = open('filePath/input.train', 'wb')
for line in myList:
f.write(bytes(line, 'UTF-8'))
f.close()

json dump generating unnecessary curly braces

This question might have been asked many times but I am still unable to understand how to use json file. I use json.dump(data, filename). While dumping I get unnecessary {} at the end of the file. So json.load(data) gives me below error.
simplejson.scanner.JSONDecodeError: Extra data: line 1 column 1865 - line 1 column 1867 (char 1864 - 1866)
I read that there is no way to load a first or second dictionary. I have also read that there is a separater which can be used with json dump but I see no use here. Should I be using encoding, decoding here?
My json.dump file:
{
"deployCI2": ["094fd196-20f0-4e8d-b946-f74a56d2f319", "6a1ce382-98c6-4058-a929-95a7d2415fd0"],
"deployCI3": ["c8fff661-4482-4908-b722-4fac0227a8b0", "929cf1fa-3fa6-4f95-8464-d58e5490f4cf"],
"deployCI4": ["9f8ffa3c-460d-43a9-8113-58e891340e1b", "6e535e92-4da2-4228-a6ab-c8fc8d31adcd", "8e26a35e-7fb9-43b3-8026-d1283f7b678c", "f40e5c29-b4df-4cfb-9d7f-3bcc9c4dcf9f"],
"HeenaStackABC": [], "HeenaStackABC-DISK_VM1-mm55lkkvccej": ["cc2a89a2-3b27-4f88-af09-b3b0b1301056"]
}{}
Edited: I think the code is doing something here.
with open('stackList.json', 'a') as f:
for stack in stacks:
try:
hlist = hc.resources.list(stack_id=stack.id)
vlist = [o.physical_resource_id for o in hlist if o.resource_type =='OS::Cinder::Volume']
myDict[stack.stack_name] = vlist
except heatclient.exc.HTTPBadRequest as e:
pass
json.dump(myDict,f)
I edited the code like below. I hope this is valid. It removed the last braces
if len(myDict) != 0:
json.dump(myDict, f)
Your problem is here :
with open('stackList.json', 'a') as f:
You're opening the file in 'append' mode, so each time the code is executed it appends the dump to your file. The result you complain about comes from this and mydict being empty on the second run.
You either have to open the file in "w" ("write") mode which will overwrite the existing content (you can eventually create a new dump file for each call) or switch to the "jsonline" format (but your file will NOT be a valid json file anymore and any code reading it will have to know to parse it as jsonlines)

Python, cannot open a text file

I have a text file named android.txt (with a couple of thousand of lines) which I try to open with python, my code is:
f = open('/home/user/android.txt', 'r')
But when I'm doing:
f.read()
the result is:
''
I chmod 777 /home/user/android.txt but the result remains the same
You are not displaying the contents of the file, just reading it.
For instance you could do something like this:
with open('/home/user/android.txt') as infp:
data = infp.read()
print data # display data read
Using with will also close the file for your automatically
The result would be empty string not empty list and it's because your file size is larger than your memory(based on your python version and your machine)! So python doesn't assigned the file content to a variable!
For getting rid of this problem you need to process your file line by line.
with open('/home/user/android.txt') as f :
for line in f:
#do stuff with line

Issue reading / writing specific lines within a log file in Python

I am attempting to print a line that contains a word from within a log file.
I have done some research and as of yet not found a good way to implement this.
I currently have this code:
FileInput = open(FILE, "r", encoding='utf-8')
for line in FileInput:
if "DATA: " in line:
print line
After looking around this seems be the way most people are doing it but I get the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found.
I know the set length from "DATA:" and the line ends with a hexadecimal value of 0A.
Either your FILE variable does not contain a proper string (can we see the value of that? can you do "print(FILE)" before trying to open the file and paste here the result?), or the file is not encoded in a way that is compatible with utf-8. Try opening it in a good editor (like jEdit or Notepad++) and see what the editor tells you it is, then specify that encoding instead of utf.
It seems you need to use
import codecs
f = codecs.open(FILE, encoding='utf-8', mode='r')
Take a look here Unicode HOWTO
try this:
FileInput = open(FILE, "r")
for line in FileInput:
if "DATA: " in line:
print(line)

Categories

Resources