I need to read a existing file that i wrote using a empty list for users raw_input. Not exactly sure on how I sort the file after reading. After sorting, i need to save it under a different file name and print.
This is what I have so far:
Names=[]
while 1:
Input = raw_input("Enter a name or press 'v' to quit:")
if Input == "v":
break
Names.append(Input)
raw_input ('Press Enter to write each of the names to a file named NAMES.')
text_file= open ("NAMES.txt", "w")
text_file.writelines(Names)
text_file.close()
raw_input('Press Enter to Read file into a sorted list.')
text_file = open("NAMES.txt", "r")
names = text_file.readlines()
text_file.close()
^This is where I need to sort and save under different file name and print. STUCK!
names.sort()
http://wiki.python.org/moin/HowTo/Sorting/
you can just sort the list of names .... names.sort()
>>> names=["John","Angel","Luis"]
>>> names.sort()
>>> names
['Angel', 'John', 'Luis']
Edit: comment answer
writelines doesn't add line separators therefore
when you do text_file.writelines(Names) you are writing just one line.
To write line separators you can do ...
text_file.writelines(map(lambda x: x+'\n',Names))
or simply append \n at the end of each name ...
Names.append(Input+'\n')
This is probably homework, so i'll give you some hints.
You should take a look at the python docs for sorting.
Using the .sort() method for a list will alter the list and give no return value.
>>> a = ['2','1']
>>> a
['2', '1']
>>> a.sort()
>>> a
['1', '2']
Using sorted() on a list, will return the list sorted, and not alter the original list:
>>> a = ['2','1']
>>> sorted(a)
['1', '2']
>>> a
['2', '1']
>>>
As far as reading in the file that you wrote, you probably want to strip the endline characters:
names = [ line.strip() for line in text_file.readlines() ]
Sort the list of names using either of the methods above, and then write to a new file.
Based on this comment:
yes, but when i try to sort it comes
back the same. Here, if I input
a,c,d,b in the raw_input it comes back
as ['acdb']
The reason why you are unable to read the names back correctly is because you are using writelines.
file.writelines(sequence)
Write a sequence of strings to the file. The sequence can be any iterable
object producing strings, typically a
list of strings. There is no return
value. (The name is intended to match
readlines(); writelines() does not add
line separators.)
You could either write the lines to your file as you ask for them:
text_file= open ("NAMES.txt", "w")
while True:
Input = raw_input("Enter a name or press 'v' to quit:")
if Input == "v":
break
text_file.write(Input)
text_file.close()
or you could append an endline character to your inputs:
Names.append(Input+"\n")
Since you aren't using the Names list anyways the first option allows you to forgo creating an unnecessary variable.
Related
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.
so far I have a text file that just says:
"the quick brown fox jumps over the lazy dog"
and my program so far looks like:
file = input("Enter File Name: ")
myList =[]
readFile = open(file, 'r')
for line in readFile:
myList.append(line.split(" "))
myList.sort()
print(myList)
the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"
The problem is that line.split(" ") creates a list of words in line, but myList.append adds this list to myList as a new single item (so you end up with a list of lists rather than list of words). What you probably wanted is:
myList.extend(line.split(" "))
You should probably read the whole file rather than one line at a time:
with open(filename) as f:
words = f.read().split()
words.sort()
This uses the default for split which splits on a space, line break or any other whitespace.
From what I observed the problem is your list of words is in a list,
myList = [["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]].
So instead of
for line in readFile:
myList.append(line.split(" "))
You should be writing
for line in readFile:
myList = line.split(" "))
The extend property works:
filename = open(input("Enter the input file name: "))
myList =[]
for line in filename:
myList.extend(line.split(" "))
myList.sort()
print(myList)
Python has two sorting functions - one which sorts the list in-place, which is what you are expecting in your code, and one which leaves the original list intact and returns a sorted list (which is what you are using). iirc the other function is called "sorted" - but now you have the info you need to look it up. This is probably also a previously asked question in stackoverflow, I encourage you look for and to link to the other ones.
def convert_table(filename_in, filename_out):
retlist = []
with open(filename_in, 'r') as fd:
for line in fd:
split = line.split(";")
for i in split:
i = i.replace(",",";")
retlist.append(i)
s = ","
s = s.join(retlist)
print(s)
with open(filename_out,'w') as fdnew:
fdnew.write(s)
return True
So when I write this output to another file, all the new lines will start with a "," such that two lines of the output are
,String,Categorical,Categorical,Int,Int,Int,Int,Float,Float,Int,Int,Int,Int,Float,Float,Float
,100% Bran,N,C,70,4,1,130,10,5,6,280,25,3,1,0.33,68.402973
How do I get rid of the comma before the word String and before the 100%?
You're reading data from the file, and putting all the data into one giant, flat list. The data you read includes line break characters, so if the file looks like
1;2;3
a;b;c
then the list you build looks like
['1', '2', '3\n', 'a', 'b', 'c\n']
and s.join(retlist) results in '1,2,3\n,a,b,c\n', with a comma after the line break.
Instead of building one giant list, building one list per line and writing one line at a time would be one way to solve your problem.
Also, it looks like you want to turn all semicolons into commas and vice versa. There's an easier way to do that than this split/replace/join stuff. Strings have a translate method to replace characters with other characters:
converted = s.translate(str.maketrans({',': ';', ';': ','}))
Is it possible that the first element of retlist is an empty string? The behavior of join doesn't start with the joining value, but if the first element is an empty string it would appear that way. For example
In [1]: l = ["", "hello", "world"]
In [2]: ','.join(l)
Out[2]: ',hello,world'
If this is the case (and an empty string doesn't provide any value to you), you could remove those from retlist before you do the join. This could be done w/ something like
l = [e for e in l if e != '']
When my script is run, it asks for an input. That input is then checked to see if it's in a text file. If it is, text is printed. The code I have below is what I have but it doesn't seem to be working, any help would be greatly appreciated!
discordname = input("What's your discord name?: ")
file = open('rtf.txt')
for line in file:
line.strip().split('/n')
if line.startswith(discordname):
file.close()
print("works")
The expression
line.strip().split('\n')
is not mutating the information bound to the name line, which remains unchanged. Instead it returns a new value. You need to bind that new value to a name in order to use use it. This example might help:
In [1]: a = " v "
In [2]: a.strip()
Out[2]: 'v'
In [3]: a
Out[3]: ' v '
In [4]: b = a.strip()
In [5]: a
Out[5]: ' v '
In [6]: b
Out[6]: 'v'
Then split('\n') (note that you probably want \ instead of /) further returns a list of substrings split by newlines. Note that this is not very useful because for line in file: already splits over lines so the list would have one element at most, and so you should omit it.
Here is the Solution:
discordname = input("What's your discord name?: ")
with open('rtf.txt', 'r') as f:
for line in f.readlines():
if line.startswith(discordname):
print ("it works")
I hope it resolve you're problem.thanks
You are probably trying to get strings as input as well. I suggest this:
discordname = raw_input("What's your discord name? ")
with open('rtf.txt') as f:
for line in f:
if discordname in line:
print "works"
You are trying to make the code more complex. Firstly to open a text file use 'with', because it is more flexible and doesn't need closing. Then, instead of using strip, you can use readlines(). This function converts each line into a list or you can also use method read(), which displays all results as it is.
So,
By using readlines, you can look through the user input in a line as a list, and by using read, you can look through each words. Here is the Solution:
discordname = input("What's your discord name? ")
with open('rtf.txt') as file:
contents = file.readlines()
if discordname in contents:
print("It exits")
Works for me, Optimized code is:
result = any(line.startswith(discordname) for line in file.splitlines())
if(result):
file.close()
print "works"
okay so I have a file that contains ID number follows by name just like this:
10 alex de souza
11 robin van persie
9 serhat akin
I need to read this file and break each record up into 2 fields the id, and the name. I need to store the entries in a dictionary where ID is the key and the name is the satellite data. Then I need to output, in 2 columns, one entry per line, all the entries in the dictionary, sorted (numerically) by ID. dict.keys and list.sort might be helpful (I guess). Finally the input filename needs to be the first command-line argument.
Thanks for your help!
I have this so far however can't go any further.
fin = open("ids","r") #Read the file
for line in fin: #Split lines
string = str.split()
if len(string) > 1: #Seperate names and grades
id = map(int, string[0]
name = string[1:]
print(id, name) #Print results
We need sys.argv to get the command line argument (careful, the name of the script is always the 0th element of the returned list).
Now we open the file (no error handling, you should add that) and read in the lines individually. Now we have 'number firstname secondname'-strings for each line in the list "lines".
Then open an empty dictionary out and loop over the individual strings in lines, splitting them every space and storing them in the temporary variable tmp (which is now a list of strings: ('number', 'firstname','secondname')).
Following that we just fill the dictionary, using the number as key and the space-joined rest of the names as value.
To print the dictionary sorted just loop over the list of numbers returned by sorted(out), using the key=int option for numerical sorting. Then print the id (the number) and then the corresponding value by calling the dictionary with a string representation of the id.
import sys
try:
infile = sys.argv[1]
except IndexError:
infile = input('Enter file name: ')
with open(infile, 'r') as file:
lines = file.readlines()
out = {}
for fullstr in lines:
tmp = fullstr.split()
out[tmp[0]] = ' '.join(tmp[1:])
for id in sorted(out, key=int):
print id, out[str(id)]
This works for python 2.7 with ASCII-strings. I'm pretty sure that it should be able to handle other encodings as well (German Umlaute work at least), but I can't test that any further. You may also want to add a lot of error handling in case the input file is somehow formatted differently.
Just a suggestion, this code is probably simpler than the other code posted:
import sys
with open(sys.argv[1], "r") as handle:
lines = handle.readlines()
data = dict([i.strip().split(' ', 1) for i in lines])
for idx in sorted(data, key=int):
print idx, data[idx]
I'm trying to make a program which bubblesorts a list of numbers from a text file. The file has one integer per line. I tried opening the file like so:
data = open(file).readlines()
but if I do this, the line breaks \n are included in the list and my bubblesort orders the number by the first digit only (i.e. 6 is after 19). Here's an example of what happens when I run my program. I first print out the unsorted list, then print the sorted list.
['13\n', '6\n', '87\n', '19\n', '8\n', '23\n', '8\n', '65']
['13\n', '19\n', '23\n', '6\n', '65', '8\n', '8\n', '87\n']
You need to convert the elements of data into ints, as files are read in as strings. Before you do the conversion, it's probably also wise to remove the \n characters, which you can do with str.strip.
Using a list comprehension:
with open(file, 'r') as f:
data = [int(line.strip()) for line in f]
I added the with context manager. It's usually good practice to use it when opening files, as it ensures that the file is afterwards. Also note that readlines isn't actually needed - iterating over a file provides each line as a string by default.
Actually, strip isn't even needed, as int automatically seems to strip whitespace. I might keep it just in case though.
int(' 13') # 13
int('13\t') # 13
int('13 \n') # 13
You want a list of integers:
int_data = [int(dat) for dat in data]
Of course, it'd be even better to do it one integer at a time instead of reading the whole file and then converting it to integers:
with open('datafile') as fin:
int_data = [int(line) for line in fin]
I'd recommend stripping the newline character and int converting. You can do this in one succinct line with a list comprehension, but a for loop would also suffice if the list comprehension syntax is confusing.
data = open(file).readlines()
out = [int(x.strip('\n') for x in data]
out.sort()
with open(filename) as f:
data = f.read().splitlines() # give list without endline chars
numbers = map(int, data)
# but be careful, this can throw ValueError on non-number strings
if you expect that not all rows can be converted to integers, write helper generator:
def safe_ints(iterable):
for item in iterable:
try:
yield int(item)
except ValueError as err:
continue
and then use:
numbers = list(safe_ints(data))