How can I store an output print data? - python

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.

Related

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()

Python Writing data to output File

def fileCounter():
infile = open('words.txt','r') # Open the source file
outfile = open('File_Results.txt','w')
data = infile.read()
lineCount = len(data.split('\n'))
wordCount = len(data.split())
charCount = len(data)
results = print(lineCount,wordCount,charCount)
infile.close()
outfile.write()
outfile.close()
fileCounter()
I'm new to coding and this is my first time working with files. How do I write results in my outfield. I keep getting this error - TypeError: write() argument must be str, not None
You need to write something. Something goes between the parentheses for outfile.write(). My guess is that you want something like this:
outfile.write("{} {} {}".format(lineCount, wordCount, charCount))
Your result = print(...) doesn't save anything. It prints to your console.
Another approach would be redirecting your prints to your file:
from contextlib import redirect_stdout
def fileCounter():
with (open('words.txt','r') as infile, open('File_Results.txt','w') as outfile):
data = infile.read()
lineCount = len(data.split('\n'))
wordCount = len(data.split())
charCount = len(data)
with redirect_stdout(outfile):
print(lineCount,wordCount,charCount)
fileCounter()
Note that I also used context managers to automatically handle opening and closing files. This approach is safer because it'll close the files (and stop redirecting STDOUT) even if an exception occurs.
There is no argument to your outfile.write() function. There needs to be some content to be written to the file, that needs to be passed as parameter to the function.
For Example:
# To write 'I am new to Python'
outfile.write('I am new to Python')
the argument to the write function must be a string.
if this line
results = print(lineCount,wordCount,charCount)
prints the stuff you want to have in the output file, you might do something like
results = "%s, %s, %s" % (lineCount,wordCount,charCount)
outfile.write(results)
outfile.close()
There are no arguments in outfile.write() so it writes nothing.
I assume you want to write the data of infile in outfile, so you do the following:
outfile.write(lineCount)
outfile.write(wordCount)
outfile.write(charCount)
In outfile.write() you wish to include whatever you're writing to file. In this case, you could do something like:
#put results into a list
results = [lineCount, wordCount, charCount]
#print results
print(results)
#write results to a file
outfile.write(",".join(results))
Two things in your code that are interesting. First, as far as I'm aware, print returns None so results in your current code is None. Second, in the corrected rendition, results is a list but in order to write it to file you need to convert it to a string. We do that by joining the elements in the list, in this case with a comma.

unable to read the data from file in 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.

How do I print the content of a .txt file in Python?

I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents on the screen, ask you if you want to edit/delete/etc the contents, do it, and then re-print out the results and ask you for confirmation to save.
I'm stuck at the printing the contents of the file. I don't know what command to use to do this. I've tried typing in several commands previously but here is the latest I've tried and no the code isn't complete:
from sys import argv
script, filename = argv
print "Who are you?"
name = raw_input()
print "What file are you looking for today?"
file = raw_input()
print (file)
print "Ok then, here's the file you wanted."
print "Would you like to delete the contents? Yes or No?"
I'm trying to write these practice codes to include as much as I've learned thus far. Also I'm working on Ubuntu 13.04 and Python 2.7.4 if that makes any difference. Thanks for any help thus far :)
Opening a file in python for reading is easy:
f = open('example.txt', 'r')
To get everything in the file, just use read()
file_contents = f.read()
And to print the contents, just do:
print (file_contents)
Don't forget to close the file when you're done.
f.close()
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop
How to read and print the content of a txt file
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
You can read this content: write the following script in notepad:
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
save it as readfile.py for example, in the same folder of the txt file.
Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip() remove notations like this: /n
print ''.join(file('example.txt'))
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
It's pretty simple
#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)
Presenting snapshot from my visual studio IDE.
single line to read/print contents of a file
reading file : example.txt
print(open('example.txt', 'r').read())
output:
u r reading the contents of example.txt file
Reading and printing the content of a text file (.txt) in Python3
Consider this as the content of text file with the name world.txt:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read() like this:
content_of_file= file.read()
Finally we will just print the content_of_file variable using print command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!

How to append a list to a file on Python using JSON

I'm getting a bit of a trouble here. I have a text file with ["Data1", "Data2", "Data3"], and I want to make that if data1 is not in the file, then append a new list with all three strings, and if data is already there, then just print it. What is broken in this code and why?
filename = "datosdeusuario.txt"
leyendo = open(filename, 'r')
if user.name in leyendo:
Print("Your user name is already there")
else:
file = open(filename, 'a')
file.write(json.dumps([user.name, "data2", "data3"])+"\n")
file.close()
Print("Since I couldn't find it, I did append your name and data.")
P.S.: I am a rookie in Python, and I'm getting confused often. That's why I am not using any dicts (no idea what they are anyway), so I'd like to make that code work in the most simple way.
P.S.2: Also, if that works, my next step would be to make a search engine to return one specific of the three data items in the list. For example, if I want to get the data2 in a list with username "sael", what would I need to do?
It seems that you're reading from the file pointer, NOT from the data in the file as you expected.
So, you first need to read the data in the file:
buffer = leyendo.read()
Then do your check based on buffer, not leyendo:
if user.name in buffer:
Also, you're opening the file two times, that may be kind of expensive. I am not sure if Python got a feature to open the file in both read and write modes.
Assuming that your user.name and your Print functions are working, you need to read the file and close the file.
Try this:
filename = "datosdeusuario.txt"
f = open(filename, 'r')
leyendo = f.read()
f.close()
if user.name in leyendo:
Print("Your user name is already there")
else:
file = open(filename, 'a')
file.write(json.dumps([user.name, "data2", "data3"])+"\n")
file.close()
Print("Since I couldn't find it, I did append your name and data.")
First, you should close the file in both cases, and I think you should close the file before re-opening it for appending.
I think the problem is with the line:
if user.name in leyendo:
which will always return false.
You should read the file and then question it like so:
if user.name in leyendo.read():

Categories

Resources