Python: Opening auto-generated file - windows

As part of my larger program, I want to create a logfile with the current time & date as part of the title. I can create it as follows:
malwareLog = open(datetime.datetime.now().strftime("%Y%m%d - %H.%M " + pcName + " Malware scan log.txt"), "w+")
Now, my app is going to call a number of other functions, so I'll need to open the file, write some output to it and close the file, several times. It doesn't seem to work if I simply go:
malwareLog.open(malwareLog, "a+")
or similar. So how should I open a dynamically created txt file that I don't know the actual filename for...?

When you create malwareLog object, it has name attribute which contains the file name.
Here's an example: (my test is your malwareLog)
import random
test = open(str(random.randint(0,999999))+".txt", "w+")
test.write("hello ")
test.close()
test = open(test.name, "a+")
test.write("world!")
test.close()
with open(test.name, "r") as f: print(f.read())
You also can store the file name in a variable before or after creating the file.
###Before
file_name = "123"
malwareLog = open(file_name, "w")
###After
malwareLog = open(random.randint(0,999999), "w")
file_name = malwareLog.name

Related

Change the delimiter in multiple CSV files from same folder and write them into a new folder

I am a newbie programmer in python and I am trying to read multiple csv files from a folder, replace the delimiter for all the csv files with 'tab' delimiter and then output these files into a new folder with replaced delimiter. So far I am stuck at the beginning.
Here is the code that I started using, this is working for a single file. But am not able to work with multiple files in same folder.
print("\nWrite same CSV File with different string(Replace ',' with tab delimiter)")
with open('Names.csv','r') as csv_file:
csv_reader = csv.reader(csv_file)
with open('Names_new.csv', 'w') as new_file:
csv_writer = csv.writer(new_file, delimiter = '\t', lineterminator='\r')
for line in csv_reader:
csv_writer.writerow(line)
Please can someone point out some tips?
Thank you in advance!
I don't think the code in your question does what you want. However, here's how to embed it in more code that will read the csv files from a specified folder for processing.
listdir takes input_folder and yields a list of all of the files in that folder.
I loop through that list and process only those files whose names end with '.csv'.
from os import listdir
import csv
input_folder = 'catalyst/'
for file_name in listdir(input_folder):
if file_name.endswith('.csv'):
print ('---> processing input file: ', file_name)
with open(input_folder + file_name,'r') as csv_file:
csv_reader = csv.reader(csv_file)
out_file_name = file_name[:-3]+'_new.csv'
print (' creating', out_file_name )
with open(input_folder + out_file_name, 'w') as new_file:
csv_writer = csv.writer(new_file, delimiter = '\t', lineterminator='\r')
for line in csv_reader:
csv_writer.writerow(line)

How to get sequence description from gi number through biopython?

I have a list of GI (genbank identifier) numbers. How can I get the Sequence description (as 'mus musculus hypothetical protein X') for each GI number so that I can store it in a variable and write it to a file?
Thanks for your help!
This is a script I wrote to pull the entire GenBank file for each genbank identifier in a file. It should be easy enough to change for your applications.
#This program will open a file containing NCBI sequence indentifiers, find the associated
#information and write the data to *.gb
import os
import sys
from Bio import Entrez
Entrez.email = "yourname#xxx.xxx" #Always tell NCBI who you are
try: #checks to make sure input file is in the folder
name = raw_input("\nEnter file name with sequence identifications only: ")
handle = open(name, 'r')
except:
print "File does not exist in folder! Check file name and extension."
quit()
outfile = os.path.splitext(name)[0]+"_GB_Full.gb"
totalhand = open(outfile, 'w')
for line in handle:
line = line.rstrip() #strips \n from file
print line
fetch_handle = Entrez.efetch(db="nucleotide", rettype="gb", retmode="text", id=line)
data = fetch_handle.read()
fetch_handle.close()
totalhand.write(data)
So, in case anybody else had that question, here is the solution:
handle=Entrez.esummary(db="nucleotide, protein, ...", id="gi or NCBI_ref number")
record=Entrez.read(handle)
handle.close()
description=record[0]["Title"]
print description
This will print the sequence description that corresponds to the identifier.

Ruby Simple Read/Write File (Copy File)

I am practicing Ruby, and I am trying to copy contents from file "from" to file "to". can you tell me where I did it wrong?
thanks !
from = "1.txt"
to = "2.txt"
data = open(from).read
out = open(to, 'w')
out.write(data)
out.close
data.close
Maybe I am missing the point, but I think writing it like so is more 'ruby'
from = "1.txt"
to = "2.txt"
contents = File.open(from, 'r').read
File.open(to, 'w').write(contents)
Personally, however, I like to use the Operating systems terminal to do File operations like so. Here is an example on linux.
from = "1.txt"
to = "2.txt"
system("cp #{from} #{to}")
And for Windows I believe you would use..
from = "1.txt"
to = "2.txt"
system("copy #{from} #{to}")
Finally, if you were needing the output of the command for some sort of logging or other reason, I would use backticks.
#A nice one liner
`cp 1.txt 2.txt`
Here is the system and backtick methods documentation.
http://ruby-doc.org/core-1.9.3/Kernel.html
You can't perform data.close — data.class would show you that you have a String, and .close is not a valid String method. By opening from the way you chose to, you lost the File reference after using it with your read. One way to fix that would be:
from = "1.txt"
to = "2.txt"
infile = open(from) # Retain the File reference
data = infile.read # Use it to do the read
out = open(to, 'w')
out.write(data)
out.close
infile.close # And finally, close it

Tempfile.new vs. File.open on Heroku

I'm capturing/creating user entered text into files from my app, attempting to temporarily store them in my Heroku tmp directory, then upload them to a cloud service such as Google Drive.
In using Tempfile I can successfully upload, but when using File.open I get the following error when attempting to upload:
ArgumentError (wrong number of arguments (1 for 0))
The error is on the call:
#client.upload_file_by_folder_id(save_path, #folder_id)
Where #client is a session with the cloud service, save_path is the location of the attached file for upload and #folder_id is the folder they should go into.
When I use Tempfile.new I am successful in doing so:
tempfile = Tempfile.new([final_filename, '.txt'], Rails.root.join('tmp','text-temp'))
tempfile.binmode
tempfile.write msgbody
tempfile.close
save_path = tempfile.path
upload_file = #client.upload_file_by_folder_id(save_path, #folder_id)
tempfile.unlink
File.open code is:
path = 'tmp/text-temp'
filename = "#{final_filename}.txt"
save_path = Rails.root.join(path, filename)
File.open(save_path, 'wb') do |file|
file.write(msgbody)
file.close
end
upload_file = #client.upload_file_by_folder_id(save_path, #folder_id)
File.delete(save_path)
Could it be that the File.path is a string, and Tempfile.path is the full path (but not as a string)? When I put out each, they look identical.
I'd like to use File as I don't want to change the filename of the existing attachments I'm uploading, whereas Tempfile appends to the filename.
Any and all assistance is greatly appreciated. Thanks!
In order for it to work using File, I needed to set the save_path to a string:
save_path.to_s

'File path' use causing program exit in Python 3

I have downloaded a set of html files and saved the file paths which I saved them to in a .txt file. It has each path on a new line. I wanted to look at the first file in the list and then itterate through the whole list, opening the files and extracting data before going on to the next file.
My code works fine with a single path put in directly (for the first file) as:
path = r'C:\path\to\file.html'
and works if I itterate through the text file using:
file_list_fp = r'C:\path\to\file_with_pathlist.txt'
with open(file_list_fp, 'r') as file_list:
for filepath in file_list:
pathend = filepath.find('\n')
path = file[:pathend]
q = open(path, 'r').read()
but it fails when I try getting a single path using either:
with open(file_list_fp, 'r') as file_list:
path_n = file_list.readline()
end = path_n.find('\n')
path_bad1 = path_n[:end]
or:
with open(file_list_fp, 'r') as file_list:
path_bad2 = file_list.readline().split('\n')[0]
With these two my code exits just after that point. I can't figure out why. Any pointers very welcome. (I'm using Python 3.3.1 on windows.)

Resources