I am trying to write a program to a file [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here's what I have.
"""
Author: Michael Wellman (wellmanm)
Title: pa10.py
Description: Deciphering a document using pennymath.
"""
def decode(inputfile,outputfile):
**inputfile = open("superDuperTopSecretStudyGuide.txt","rU").read()
outputfile = open("translatedguide.txt","w")**
count = 0
aList = []
for words in inputfile:
aList.append(words)
charCount = len(aList)
**outpufile.write(aList)**
while count<charCount:
print aList[count],
if (aList[count].isalpha()):
if (ord(aList[count])>90):
count = count + ord(aList[count])-95
else:
count = count + ord(aList[count])-63
else:
if (aList[count].isdigit()):
count = count + ord(aList[count])-46
else:
count = count + 6
**inputfile.close()
outputfile.close()**
The txt files are from my professor :P
The parts bolded are the most important, I believe.
Any thoughts?

Have you tried running the code?
I think if you would you'd get an error message about the line
outpufile.write(aList)
See, the doc string for file.write() method clearly states:
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
You are supplying it a list instead of a str. Try changing it to
outpufile.write(''.join(aList))
or
outputfile.write(aList[-1])
or whatever fits your needs. Also, you never clear the list, so, as you iterate over inputfile, you'll write the first character, then the first and the second, then the first three, etc. Is that intended?
Lastly, you are trying to close inputfile which is actually a str, not a file, because file.read() method returns a str.
P.S. Please, never call your variable inputfile if it's a string and words if it's a single character. That will never help anyone.

Related

Python3 float to int from load file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am beginner in python and I have a file with e.g data:
123.141212412
123124.5436456
13123.123546
I am trying to convert it to inteeger.
My idea was load file to a list and format the records. But it throws an error.
I did:
file.write(str(format(list1,'.0f')))
You may perform the same in this manner :
file = open('test.txt', 'r')
# List to hold the numbers
x = []
# end = split at \n because \n is read in lines too
for line in file.read().split('\n'):
# Type casting to int
int_num = int(float(line))
# saving the int part of the data in list
x.append(int_num)
# printing the int part
print(int_num)
You cannot directly apply format on a list, you have to loop through your list to do so, like this:
for number in list1:
file.write(format(number, ".0f") + "\n")
Of course, this assumes file exists and have been correctly defined, like this:
file = open("my_filename", "w")

Python take the string of anything, ignoring all escape characters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to make a function that takes typically copy-pasted text that very often includes \n characters. An example of such is as follows:
func('''This
is
some
text
that I entered''')
The problem with this function is the text can sometimes be rather large, so taking it line by line to avoid ', " or ''' isn't plausible. A piece of text that can cause issues is as follows:
func('''This
is'''
some"
text'
that I entered''')
I wanted to know if there is any way I can take the text as seen in the second example and use it as a string regardless of what it is comprised of.
Thanks!
To my knowledge, you won't be able to paste the text directly into your file. However, you could paste it into a text file.
Use regex to find triple quotes ''' and other invalid characters.
Example python:
def read_paste(file):
import re
with open(file,'r') as f:
data = f.readlines()
for i,line in enumerate(data):
data[i] = re.sub('("|\')',r'\\\1',line)
output = str()
for line in data:
output += line
return output

Split a string by a comma and cast the second half as an int [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
With the following expected input:
[u'able,991', u'about,11', u'burger,15', u'actor,22']
How can I split each string by the comma and return the second half of the string as an int?
This is what I have so far:
def split_fileA(line):
# split the input line in word and count on the comma
<ENTER_CODE_HERE>
# turn the count to an integer
<ENTER_CODE_HERE>
return (word, count)
One of the first things you'll need in learning how to code, is to get to know the set of functions and types you have natively available to you. Python's built-in functions is a good place to start. Also get the habit of consulting the documentation for the stuff you use; it's a good habit. In this case you'll need split and int. Split does pretty much what it says, it splits a given string into multiple tokens, given a separator. You'll find several examples with a simple search in google. int, on the other hand, parses a string (one of the things it does) into a numeric value.
In your case, this is what it means:
def split_fileA(line):
# split the input line in word and count on the comma
word, count = line.split(',')
# turn the count to an integer
count = int(count)
return (word, count)
You won't get this much here in stackoverflow, has other users are often reluctant to do your homework for you. It seems to me that you are at the very beginning of learning how to code so I hope this helps you get started, but remember that learning is also about trial and error.

How do I read a text file into a string variable in Python starting at the second line? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I use the following code segment to read a file in python
file = open("test.txt", "rb")
data=file.readlines()[1:]
file.close
print data
However, I need to read the entire file (apart from the first line) as a string into the variable data.
As it is, when my files contents are test test test, my variable contains the list ['testtesttest'].
How do I read the file into a string?
I am using python 2.7 on Windows 7.
The solution is pretty simple. You just need to use a with ... as construct like this, read from lines 2 onward, and then join the returned list into a string. In this particular instance, I'm using "" as a join delimiter, but you can use whatever you like.
with open("/path/to/myfile.txt", "rb") as myfile:
data_to_read = "".join(myfile.readlines()[1:])
...
The advantage of using a with ... as construct is that the file is explicitly closed, and you don't need to call myfile.close().

Transforming sequence of pure characters into separate float numbers in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have thousands of lines with data in the form: 6580,f|S,17:42:29.3,-39:01:48,2.19,2.41,-0.22
I would like to take only the last number (in this case -0.22) so I can perform some calculations.
My problem is: the lines aren't strings, and they have variable length (slicing from the beginning/end isn't an option). How can separate those commas and create a list of strings or floats?
Is there a way to separate that sequence in way that I can use, for example, "line[6]" to get that last value?
If the floating number you need is always the last entry in comma-separated line, float(line.split(',')[-1]) should do the trick.
Otherwise I would do something like the following:
def isFloat(val):
try:
float(val)
return True
except ValueError:
return False
number = [x for x in line.split(',') if isFloat(x)][-1]
If all the lines you have are stored in a text file, open it and process your lines:
with open("my_file.txt") as f:
for line in f:
# Here goes the code where you're getting the floating number from the line
Maybe you're looking for this syntax line[:-1] will always give you the last element in an array.
It could possibly be line[::-1]. Somebody should correct me if I'm wrong.
BTW if they are not strings, what are they?
Edit.
It's line[-1], Getting the last element of a list in Python

Categories

Resources