os.path.join does not yield the contents of the file - python

print "Which category would you like to view? Savory, Dessert, Cake, Soup or Drink? "
category = raw_input()
for x in os.listdir(category): print x
name = raw_input("Which recipe would wou like to view? ")
fullname = os.path.join(category, name)
f = open(fullname, "r");
print f
I am writing a program that will allow users to view the contents of .txt files saved in specific directories. When I run this code I don't get the contents and instead get a message that says this:
open file 'savory/b.txt', mode 'r' at 0x1004bd140
any ideas. I am new to python so i dont have much of an idea as to what is causing the error but i assume it is due to some missing code.
Thank you.

The return value of open is a file object (not the file contents!) .You need to call a method on your file object to actually read the file:
f = open(fullname, "r")
print f.read()
f.close()
If it's a big file you may want to iterate over the file line-by-line
f = open(fullname, "r")
for line in f:
print line
f.close()
On a side note, here's alternate syntax to you don't have to remember to call the close method:
with open(fullname, "r") as f:
for line in f:
print line

Related

How to fix " AttributeError: 'int' object has no attribute 'replace' " while replacing and writing to a new file?

I have a hello.py file which asks user for their name and prints them a welcome message.
import subprocess
filename = "hello-name.txt"
fout = open("out.txt", "w")
with open(filename, "r+") as f:
lines = f.readlines()
your_name = input("What is your name? ")
title_name = your_name.title()
for line in lines:
line = fout.write(line.replace("[Name]", your_name))
line = fout.write(line.replace("[Title]", title_name))
print(line.strip())
subprocess.call(["notepad.exe", "out.txt"])
This is the content of my hello-name.txt file
Hello [Name]
Welcome to the world [Title]
My Question
When run hello.py it asks user for their Name and as soon as the name is entered, Python gives the following error :
line = fout.write(line.replace("[Title]", title_name))
AttributeError: 'int' object has no attribute 'replace'
Kindly help me to fix this issue.
Thank You
The write method returns the number of characters written, not the value written. Don't assign the result to line if you want to keep using it. If the goal is to perform both replacements before writing, do them both, then write, e.g.:
for line in lines:
line = line.replace("[Name]", your_name)
line = line.replace("[Title]", title_name)
fout.write(line)
There are two problems with this script:
As ShadowRanger pointed out, you're assigning the result from write to line; this overwrites the content.
You don't close the output file before opening it in Notepad.
An easy way to make sure a file is closed is to open it in a context, using the with keyword. You already did this when you read the input file; just do the same thing for the output file, and open Notepad after the with block (i.e. after you've written both lines and closed the file):
import subprocess
with open("hello-name.txt", "r+") as f:
lines = f.readlines()
your_name = input("What is your name? ")
title_name = your_name.title()
with open("out.txt", "w") as fout:
for line in lines:
line = line.replace("[Name]", your_name)
line = line.replace("[Title]", title_name)
fout.write(line)
print(line.strip())
subprocess.call(["notepad.exe", "out.txt"])
The return from fout.write is an integer. Then you are trying to replace on an integer (it isn't giving you the replaced line.
Try:
import subprocess
filename = "hello-name.txt"
fout = open("out.txt", "w")
with open(filename, "r+") as f:
lines = f.readlines()
your_name = input("What is your name? ")
title_name = your_name.title()
for line in lines:
line = line.replace("[Name]", your_name)
line = line.replace("[Title]", title_name)
fout.write(line)
print(line.strip())
fout.close()
subprocess.call(["notepad.exe", "out.txt"])
I changed it to a single fout since my guess is you don't want the double printing (but you can change it back). You probably also want to make the notepad call after parsing everything (and closing the file as others have mentioned)

How to open and print the contents of a file line by line using subprocess?

I am trying to write a python script which SSHes into a specific address and dumps a text file. I am currently having some issues. Right now, I am doing this:
temp = "cat file.txt"
need = subprocess.Popen("ssh {host} {cmd}".format(host='155.0.1.1', cmd=temp),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(need)
This is the naive approach where I am basically opening the file, saving its output to a variable and printing it. However, this really messes up the format when I print "need". Is there any way to simply use subprocess and read the file line by line? I have to be SSHed into the address in order to dump the file otherwise the file will not be detected, that is why I am not simply doing
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
Any help would be appreciated :)
You don't need to use the subprocess module to print the entire file line by line. You can use pure python.
f = open(temp, "r")
file_contents = f.read()
f.close()
# turn the file contents into a list
file_lines = file_contents.split("\n")
# print all the items in the list
for file_line in file_lines:
print(file_line)

Attempt to use the open() function failing

I'm trying to learn to manipulate files on python, but I can't get the open function to work. I have made a .txt file called foo that holds the content "hello world!" in my user directory (/home/yonatan) and typed this line into the shell:
open('/home/yonatan/foo.txt')
What i get in return is:
<_io.TextIOWrapper name='/home/yonatan/foo.txt' mode='r' encoding='UTF-8'>
I get what that means, but why don't I get the content?
open() returns a file object.
You then need to use read() to read the whole file
f = open('/home/yonatan/foo.txt', 'r')
contents = f.read()
Or you can use readline() to read just one line
line = f.readline()
and don't forget to close the file at the end
f.close()
An example iterating through the lines of the file (using with which ensures file.close() gets called on the end of it's lexical scope):
file_path = '/home/yonatan/foo.txt'
with open(file_path) as file:
for line in file:
print line
A great resource on I/O and file handling operations.
You haven't specified the mode you want to open it in.
Try:
f = open("home/yonatan/foo.txt", "r")
print(f.read())

string.replace method in python

I am a newbie with python, so kindly excuse for asking basic question.
I am trying to use the string.replace method in python and getting a weird behavior. here is what I am doing:
# passing through command line a file name
with open(sys.argv[2], 'r+') as source:
content = source.readlines()
for line in content:
line = line.replace(placeholerPattern1Replace,placeholerPattern1)
#if I am printing the line here, I am getting the correct value
source.write(line.replace(placeholerPattern1Replace,placeholerPattern1))
try:
target = open('baf_boot_flash_range_test_'+subStr +'.gpj', 'w')
for line in content:
if placeholerPattern3 in line:
print line
target.write(line.replace(placeholerPattern1, <variable>))
target.close()
When I am checking the values in the new file, then these are not replaced. I could see that the value of the source is also not changed, but the content had changed, what am I doing wrong here?
Rather do something like this -
contentList = []
with open('somefile.txt', 'r') as source:
for line in source:
contentList.append(line)
with open('somefile.txt','w') as w:
for line in contentList:
line = line.replace(stringToReplace,stringToReplaceWith)
w.write(line)
Because with will close your file after runing all the statements wrapped within it, which means the content local variable will be nil in the second loop.
You are reading from the file source and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.
Try this:
# Read the file into memory
with open(sys.argv[2], 'r') as source:
content = source.readlines()
# Fix each line
new_content = list()
for line in content:
new_content.append(line.replace(placeholerPattern1Replace, placeholerPattern1))
# Write the data to a temporary file name
with open(sys.argv[2] + '.tmp', 'w') as dest:
for line in new_content:
dest.write(line)
# Rename the temporary file to the input file name
os.rename(sys.argv[2] + '.tmp', sys.argv[2])

Python command isn't reading a .txt file

Trying to follow the guide here, but it's not working as expected. I'm sure I'm missing something.
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
file = open("C:/Test.txt", "r");
print file
file.read()
file.read()
file.read()
file.read()
file.read()
file.read()
Using the readline() method gives the same results.
file.readline()
The output I get is:
<open file 'C:/Test.txt', mode 'r' at 0x012A5A18>
Any suggestions on what might be wrong?
Nothing's wrong there. file is an object, which you are printing.
Try this:
file = open('C:/Test.txt', 'r')
for line in file.readlines(): print line,
print file invokes the file object's __repr__() function, which in this case is defined to return just what is printed. To print the file's contents, you must read() the contents into a variable (or pass it directly to print). Also, file is a built-in type in Python, and by using file as a variable name, you shadow the built-in, which is almost certainly not what you want. What you want is this:
infile = open('C:/test.txt', 'r')
print infile.read()
infile.close()
Or
infile = open('C:/test.txt', 'r')
file_contents = infile.read()
print file_contents
infile.close()
print file.read()
You have to read the file first!
file = open("C:/Test.txt", "r")
foo = file.read()
print(foo)
You can write also:
file = open("C:/Test.txt", "r").read()
print(file)

Categories

Resources