User prompt as file to read

Dave Angel davea at
Sat Mar 22 15:34:25 CET 2014

 kjakupak at Wrote in message:
> I'm trying to create a program that will prompt the user for a list of text files to read from, then read those text files and build a dictionary of all the unique words found. Then finally put those unique words into another file and make it alphabetical order.

Specify python version and os.  I assume python 3 and Windows. 

> What I've got:
> import string
> s = input("Enter a file name: ") + ".txt"
> filepath = "I:\\" + s

So you've got a filename.  You're not using it for anything.
 Where's your open? Where's your read or readline?

> # remove all punctuation marks and make lower case
> s_nopunct = "".join(c for c in s if c not in string.punctuation).lower()

Are you sure you want a single string nearly the total size of
 your 3 files? Could be huge. Might be better to do it

It's a lot safer to include the characters you want,  instead of
 excluding some of the ones you don't.  And many valid words
 contain punctuation such as apostrophe. 

> # convert to a sorted list of unique words via set comprehension
> list_unique = sorted(list({word for word in s_nopunct.split()}))

> print("\nSorted list of unique words in sentence:")
> print(list_unique)
> with open("C:\\Users\\Desktop\\words.dat", "w") as f:
>     for x in list_unique:
>         f.write(x + "\n")
> I need help making it so that the user is prompted to enter at least 3 files.

Need a while loop for that. 

> And also, I tried making those unique words to write to another file (I got it that far), but how do I make it more of an arbitrary path (rather than the C:\Users etc) since I need it so that anyone can run that program and write/find to that file.

That could be another input, or it could be a command line
 parameter.  Your choice. 


More information about the Python-list mailing list