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.
Related
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')
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+")
I have a for loop which creates a CSV of values of several files in a directory.
Within this loop I only want to create the file and write in the header once, currently I am doing this:
#name&path to table file
test = tablefile+"/"+str(cell[:-10])+"_Table.csv"
#write file
if not os.path.isfile(test):
csv.writer(open(test, "wt"))
with open(test, 'w') as output:
wr = csv.writer(output, lineterminator=',')
for val in header_note:
wr.writerow([val])
and to append data I have:
with open(test, 'a') as output:
wr = csv.writer(output, lineterminator=',')
for val in table_all:
wr.writerow([val])
Which works well, however, when I run the script over again another time it will append more data to the bottom of that same .csv. What I want is for the first time through the for-loop, is to just overwrite any existing .csv with a new one with a header then continue on appending data, and overwrite/re-write header once the script is run again. Thanks!
It look like you may have some code problems other than file handling, but here goes: You problem is basically that opening a file in 'w' mode will overwrite everything in the file, and opening in 'a' mode will not allow you to change the header line.
To get around this, you will have to get the contents of the file (if it already exists), then overwrite the file, including those lines that where there to begin with.
You will want something along the lines of:
if os.path.exists(file_name): # if file already exists
with open(file_name, 'r') as in_file: # open it
old_lines = in_file.readlines()[1:] # read all lines from file EXCEPT header line
with open(file_name, 'w') as out_file: # open file again, with 'w' to create/overwrite
out_file.write(new_header_line) # write new header line to file
for line in old_lines:
out_file.write(line) # write all preexisting lines back into file
# continue writing whatever you want.
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
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.