Reading file doesn't work in python - python-2.7

I am trying to open a file but it is displaying nothing.
openf = open('C:\Python27\NEWS', 'r')
openf.read()
It is neither displaying text nor any error. What could be the reason?
and when i write like this
openf = open('C:\Users\K\Desktop\wait.txt', 'r')
>>> print openf
This gives Output:
<open file 'C:\\Users\\K\\Desktop\\wai.txt', mode 'r' at 0x0000000002B4DDB0>
What does this mean?

read doesn't display anything - it merely returns a string. If you're not at an interactive prompt, the only output you will see is what you print.
openf = open('C:\Python27\NEWS', 'r')
print openf.read()
print openf will give details about the openf object. It's an open file pointed at that file name, it was opened in "read" mode, and it exists in memory at address 0x0000000002B4DDB0.

Related

Issue with writing multiple lines into a file in python

I want to download multiple specific links(images´ urls) into a txt file(or any file where all links can be listed underneath each others).
I get them but the code wrtite each link on the top of the other one and at the end it stays only a link :(. Also I want not repeated urls
def dlink(self, image_url):
r = self.session.get(image_url, stream=True)
with open('Output.txt','w') as f:
f.write(image_url + '\n')
The issue is most simply that opening a file with mode 'w' truncates any existing file. You should change 'w' to 'a' instead. This will open an existing file for writing, but append instead of truncating.
More fundamentally, the problem may be that you are opening the file over and over in a loop. This is very inefficient. The only time the approach you use could be really useful is if your program is approaching the OS-imposed limit on number of open files. If this is not the case, I would recommended putting the loop inside the with block, keeping the mode as 'w' since you open the file just once now, and passing the open file to your dlink function.
Edit
Huge mistake of my part, as it is a method, and you will call it several times, if you open it in write mode ('w') or similar, it will Overwrites the existing file if the file exists.
So, if you use the 'a' way, you can see that:
Opens a file for appending. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.
The other problem radics in image_url is a list, so you need to write it line by line:
def dlink(self, image_url):
r = self.session.get(image_url, stream=True)
with open('Output.txt','a') as f:
for url in list(set(image_url)):
f.write(image_url + '\n')
another way to do it:
your_file = open('Output.txt', 'a')
r = self.session.get(image_url, stream=True)
for url in list(set(image_url)):
your_file.write("%s\n" % url)
your_file.close() #dont forget close it :)
the file open mode is wrong,'w' mode make this file was overwritten every time you open it,not appended to it. replace it to 'a' mode.
you can see this https://stackoverflow.com/a/23566951/8178794 for more detail
Open a file with option w overwrite the file if existring, use the mode a to append data to an existing file.
Try :
import requests
from os.path import splitext
# use mode='a' to append result without erasing filename
def dlink(url, filename, mode='w'):
r = requests.get(url)
if r.status_code != 200:
return
# here the link is valid
with open(filename, mode) as desc:
desc.write(url)
def dimg(img_url, img_name):
r = requests.get(img_url, stream=True)
if r.status_code != 200:
return
_, ext = splitext(img_url)
with open(img_name + ext, 'wb') as desc:
for chunk in r:
desc.write(chunk)
dlink('https://image.flaticon.com/teams/slug/freepik.jpg', 'links.txt')
dlink('https://image.flaticon.com/teams/slug/freepik.jpg', 'links.txt', 'a')
dimg('https://image.flaticon.com/teams/slug/freepik.jpg', 'freepik')

With below code I'm trying to write to a file in Python but I am getting an error

Here is the error:
Here is the code.
from sys import argv
first,second=argv
file1=open(second)
print file1.read()
file2=open(second)
file2.write("this is a new line being added to this file\n\n Did you recognize??")
print "check after writing to the file"
print file2.read()
You need to pass second parameter while opening second file.
file2=open("second.txt", "a+")
file2.write("text")
file2.close
a parameter means that you can append text to file.
w parameter means that you can write new text to file.
r parameter means that you are in read only mode.
file 2 should be opened in write mode!
file2 = open(second,"w")
or as r+ mode, that is read and write mode!
file2 = open(second,"r+")

Writing in files

I have been trying to write onto a file while using python but for some reason it keeps writing onto my console and not my created file. Yes I know this question has been asked before and yes i have used the .close() command. Here is my block of code.
myfile= open ('C:/Users/12345/Documents/Grouped_data.txt','r')
with open ('C:/Users/12345/nanostring.txt','w') as output:
for line in myfile:
Templist= line.split()
print line
print Templist[0], Templist[4], Templist[5],Templist[6], Templist[7], Templist[8], Templist[9], Templist[10], Templist[12]
print output
myfile.close()
output.close()
This should be as simple as:
>>> with open('somefile.txt', 'a') as the_file:
... the_file.write('Hello\n')
From The Documentation:
Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.
In python 2.7,
You can use >> after the print and use as name
So here it is print>>output,line
myfile= open ('C:/Users/12345/Documents/Grouped_data.txt','r')
with open ('C:/Users/12345/nanostring.txt','w') as output:
for line in myfile:
Templist= line.split()
print>>output,line # Note the changes
print>>output,Templist[0], Templist[4], Templist[5],Templist[6], Templist[7], Templist[8], Templist[9], Templist[10], Templist[12] # Note the changes
Note: print directly prints in terminal and print>>as name, prints to file.

LPTHW Ex 16, imy ssues with my own script

I successfully completed ex16 in LPTHW and now I'm trying to replicate it in my own script to better understand the lesson. I typed the following but the shell returns with:
File "bruce.py", line 23, in
scribble.truncate()
I0Error: File not open for writing
My script is as follows:
from sys import argv
script, file_name=argv
scribble=open(file_name)
print "Master Bruce, here is your file: %s" % file_name
print scribble.read()
print """
Master Bruce, to change the contents of the file
simply press ENTER and type three lines:
"""
line1=raw_input("line 1:")
line2=raw_input("line 2:")
line3=raw_input("line 3:")
print "Just a few seconds Master Bruce..."
scribble.truncate()
scribble.write(line1,line2,line3)
scribble.close
My understanding is that the file was opened in line 5 already. I also tried scibble.open() on line 22 but that didnt work either. Your help is appreciated.
It means exactly what it says: the file isn't open for writing. You opened it in read-only mode.
scribble=open(file_name)
is equivalent to
scribble=open(file_name, "r")
You need to open the file in read/write mode. Since you don't want to truncate it at the start and don't want to append to it, use r+.
scribble=open(file_name, "r+")
You should brush up on the documentation for open() here.
Incidentally, you should also look into opening files with the with keyword here for cleaner handling.
with open(file_name, "r+") as scribble:
# do things
...
The most commonly-used values of mode are 'r' for reading [...]. If mode is omitted, it defaults to 'r'.
[...]
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file.
source

Python - Is it recommended to always open file with 'b' mode?

So I have this simple python function:
def ReadFile(FilePath):
with open(FilePath, 'r') as f:
FileContent = f.readlines()
return FileContent
This function is generic and used to open all sort of files. However when the file opened is a binary file, this function does not perform as expected. Changing the open() call to:
with open(FilePath, 'rb') as f:
solve the issue for binary files (and seems to keep valid in text files as well)
Question:
Is it safe and recommended to always use rb mode for reading a file?
If not, what are the cases where it is harmful?
If not, How do you know which mode to use if you don't know what type of file you're working with?
Update
FilePath = r'f1.txt'
def ReadFileT(FilePath):
with open(FilePath, 'r') as f:
FileContent = f.readlines()
return FileContent
def ReadFileB(FilePath):
with open(FilePath, 'rb') as f:
FileContent = f.readlines()
return FileContent
with open("Read_r_Write_w", 'w') as f:
f.writelines(ReadFileT(FilePath))
with open("Read_r_Write_wb", 'wb') as f:
f.writelines(ReadFileT(FilePath))
with open("Read_b_Write_w", 'w') as f:
f.writelines(ReadFileB(FilePath))
with open("Read_b_Write_wb", 'wb') as f:
f.writelines(ReadFileB(FilePath))
where f1.txt is:
line1
line3
Files Read_b_Write_wb, Read_r_Write_wb & Read_r_Write_w eqauls to the source f1.txt.
File Read_b_Write_w is:
line1
line3
In the Python 2.7 Tutorial:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
On Windows, 'b' appended to the mode opens the file in binary mode, so
there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows
makes a distinction between text and binary files; the end-of-line
characters in text files are automatically altered slightly when data
is read or written. This behind-the-scenes modification to file data
is fine for ASCII text files, but it’ll corrupt binary data like that
in JPEG or EXE files. Be very careful to use binary mode when reading
and writing such files. On Unix, it doesn’t hurt to append a 'b' to
the mode, so you can use it platform-independently for all binary
files.
My takeaway from that is using 'rb' seems to the best practice, and it looks like you ran into the problem they warn about - opening a binary file with 'r' on Windows.