I want to save the output as a text file on my system. The name of the output file should get from the user in command prompt.
output = input("Enter a name for output file:")
my_file = open('/output.txt', "w")
for i in range(1, 10):
my_file.write(i)
Is this correct way of doing??
Do like this
output = raw_input("Enter a name for output file:")
my_file = open(output + '.txt', "w")
for i in range(1, 10):
my_file.write(str(i))
You can do the following:
import os
# you can use input() if it's python 3
output = raw_input("Enter a name for output file:")
with open("{}\{}.txt".format(os.path.dirname(os.path.abspath(__file__)), output), "w") as my_file:
for i in range(1, 10):
my_file.write("".format(i))
At this example we are using the local path by using os.path.dirname(os.path.abspath(__file__)) we will get the current path and we will add it output.txt
To read more about abspath() look here
To read more about with look here
write method in you case will raise a TypeError since i needs to be a string
So couple of changes I made. You need to do something like:
output + '.txt'
to use the variable output as the file name.
Apart from that, you need to convert the integer i to a string by calling the str() function:
str(i)
becuase the write function only takes strings as input.
Here is the code all together:
output = raw_input("Enter a name for output file: ")
my_file = open(output + '.txt', 'wb')
for i in range(1, 10):
my_file.write(str(i))
my_file.close()
Hope this helps!
You can do it in one line so you will have your txt file in your .py file path:
my_file=open('{}.txt'.format(input('enter your name:')),'w')
for i in range(1, 10):
my_file.write(str(i))
my_file.close()
Note: if you are using python 2.x use raw_input() instead of input .
Related
I am trying to use three files in which the first is the text file that contains the names of 3 different zip files. I then want to open those 3 files and write their contents into a separate text file. I have the pseudocode for this program but I am unable to figure out what to do. I have some code but I don't know if it is correct for this program. I am not very advanced in python yet so I would like to run this code using concept that are mostly in my code or easier code that can help me get a walk through of how to make and run this program.
Pseudocode:
Input File – List of zip file names with location
Read each line from the input file, read the contents of the zip file and write it to the output file
Output File – print the list of the files/contents inside the zip file
Here is the code I have so far:
import zipfile
write_file = open('file.txt' , "w")
input_file = open('C:\\Users\\Tanish L\\OneDrive\\InputReadFile.txt','r')
i = 0
readfile = input_file.readlines()
a = True
for line in readfile:
while a == True:
print(readfile[0:i])
i = int(i) + 1
if i > len(readfile):
a = False
file_names = zipfile.ZipFile(#file line from input_file,'r')
for name in file_names.namelist():
write_file.write('%s' % (name) + "\n")
file_names.close()
write_file.close()
import zipfile
write_file = open('file.txt' , "w")
input_file = open('C:\\Users\\Tanish L\\OneDrive\\InputReadFile.txt','r')
i = 0
readfile = input_file.readlines()
for line in readfile:
f = zipfile.ZipFile(line.rstrip())
for name in f.namelist():
write_file.write(name + "\n")
f.close()
write_file.close()
Explanation:
You already loop over the lines in readfile (array) with the for loop and don't need a counter controlled while loop as well.
You then open the zipfile with the filename of that line (rstrip removes the newline '\n' at the end).
Then loop over the files in the zip file using namelist, and write that to your write file.
I am trying to generate the reverse complement for DNA sequences of multiple file types with a python script. Here is what I have written so far
import gzip
import re
############## Reverse Complement Function #################################
def rev_comp(dna):
dna_upper = dna.upper() #Ensures all input is capitalized
dna_rev = dna_upper[::-1] #Reverses the string
conversion = {'A':'T','C':'G','G':'C','T':'A','Y':'R','R':'Y',\
'S':'S','W':'W','K':'M','M':'K','B':'V','V':'B',\
'D':'H','H':'D','N':'N','-':'-'}
rev_comp = ''
rc = open("Rev_Comp.fasta", 'w')
for i in dna_rev:
rev_comp += conversion[i]
rc.write(str(rev_comp))
print("Reverse complement file Rev_Comp.fasta written to directory")
x = input("Enter filename (with extension) of the DNA sequence: ")
if x.endswith(".gz"): #Condition for gzip files
with gzip.open(x, 'rb') as f:
file_content = f.read()
new_file = open("unzipped.fasta", 'w')
new_file.write(str(file_content))
print("unzipped.fasta written to directory")
xread = x.readlines()
fast = ''
if x.endswith(".fasta"): #condition for fasta files
for i in xread:
if not i.startswith('>'):
fast = fast + i.strip('\n')
if x.endswith(".fastq"): #condition for fastq files
for i in range(1,len(xread),4):
fast = fast + xread[i].strip('\n')
rev_comp(x)
And what I wind up with is
AttributeError: 'str' object has no attribute 'readlines'
when I try to run the script using a .fastq file. What exactly is going wrong here? I expect the script to write Rev_comp.fasta, but it doesn't.
x is not a filehandle, just a file name. You need to do
with open(x) as xhandle:
xread = xhandle.readlines()
The overall logic might be better if you don't read all lines into memory. Also, the .gz case ends up in vaguely undefined territory; do you need to set x to the name of the unzipped data at the end of the gz handling, or perhaps put the code after it into an else: branch?
x is the input from the user, which is a string. You need to open a file to be able to call readlines on it.
According to your existing code:
x = input("Enter filename (with extension) of the DNA sequence: ") # x stores a string
file_x = open(x, 'r') # You must open a file ...
xread = file_x.readlines() # and call readlines on the file instance.
# Although it is not explicitly necessary, remember to close the file when you'done, is good practice.
file_x.close()
or use the file as a context manager
with open(x) as file_x:
xread = file_x.readlines()
I have a txt file with strings assigned to each other like "sun - moon" and I want to get the assigned value (no matter which one) of a particular string if it would come from user input, and if not then create a new pair for file and write it to it:
user_input = input()
if user_input in open('base.txt').read():
print(True) # it's just to be sure that everything really works
else:
base_file = open('base.txt', 'a+')
base_file.write(user_input)
base_file.write('\n')
base_file.close()
import pickle
myDictA = {'sun': 'moon'}
with open('myFile.pkl', 'w') as file:
pickle.dump(myDict, file)
with open('myFile.pkl', 'r') as file:
myDictB = pickle.load(file)
print("myDictA:", myDictA)
print("myDictB:", myDictB)
you can also integrate gzip in the file save load process to save disk space if you want. Another option is to use cPickle which should be written the same way and is said to be up to 1000x faster.
A little addition to the current code.
user_input = input()
flag=1
with open('base.txt') as f:
data=f.read()
if user_input in data:
print(data)
flag=0
if flag:
base_file = open('base.txt', 'a+')
base_file.write(user_input)
base_file.write('\n')
base_file.close()
I'm trying to get the below function running from the command line by simply using
python filename.py
However, it isn't doing what I want.
Could someone please help me out with this? I'm sure I'm missing something very simple...
inFile = ""
inFile = raw_input("Enter the File Name: ")
x = open(inFile, 'w')
def summation(x):
sum = 0
for i in x:
sum = sum + i
return sum
if __name__ == "__main__":
print(summation(x))
Hopefully it's fairly self explanatory what I'm trying to achieve, but in case it's not...
I'm asking for a raw_input; this will be a text file full of numbers (each on it's own line). The file should be fed into the variable x which is then used in the summation function. Finally, with a for loop each value is summed and the sum is returned (and printed in terminal).
There are two problems:
You're opening the file in write mode. This deletes all the contents of the file. Drop the "w" parameter.
You can't add strings (as read from the file) to an integer. You need to convert them to integers first: sum += int(i)
Also, you should close the file after you've read its contents. And the line infile = "" is unnecessary.
A more pythonic version...
def line_to_int(line):
line = line.strip()
if not line:
# handles the case of empty lines
return 0
return int(line)
def sumfile(f):
return sum(line_to_int(line) for line in f)
if __name__ == "__main__":
fname = raw_input("Enter the File Name: ").strip()
with open(fname) as f:
print(sumfile(f))
or even more simple as long as you don't plan on adding error handling around the call to int(line) (thanks Jon Clements):
if __name__ == "__main__":
fname = raw_input("Enter the File Name: ").strip()
with open(fname) as f:
print(sum(int(line.strip() or 0) for line in f))
Hello I am trying to build a tool that will compress a list of folders and rename the compressed file, this list of the names of folders I want to compress are located in a .txt file, the .txt is something like this:
james, 5005
kyle, 02939
Betty, 40234
I have used multiple methods to try and build this code but I keep getting a python error set object is not subscriptable and I have no idea what to do to rectify this and on how to continue from here. Can I not use shutil.make_archive with dictionaries or can I use lists? because I would like to run this function down the first column and to rename the files i am creating using the second column. I am using python 3, and any help would be great!
import os
import shutil
x = input("Input Path your user list: ")
filename = input("Input user file name: ")
changedir = input("Input where your folders are: ")
os.chdir(changedir)
userfile = x + filename + ".txt"
print("Awesome your path is now", userfile)
with open(userfile, "rt") as userfileone:
count = 0
while 1:
buffer = userfileone.read(8192*1024)
if not buffer: break
count += buffer.count('\n')
print("It is indicated that there are", count + 1, "in the file")
with open(userfile, "rt") as f:
lines = f.readlines()
dic = {}
for x in lines:
x = x.strip().split(',')
dic[x[0]]=tuple(x[1:])
for i in dic:
shutil.make_archive(i, "zip", dic[i])
It seems like you are looking for the map function.