Reading and Writing

E

elias.goodman

I am new to Python and programming. I am looking for some basic
instruction here.

How should I: Open a Text file, read from it, modify it, print to
another .txt?

For instance: Read a string, sort it, write the sorted string.

I understand the algorithms but I don't know the actual mechanics of
Python.

Any help or advice as to where to look would be great.

Thanks.
 
S

Sir Galahad the chaste

Hi,

How should I: Open a Text file, read from it, modify it, print to
another .txt?

For instance: Read a string, sort it, write the sorted string.

What do you mean by "sorting"? If you want to sort the lines contained
in a file, you could do something like this.

$ cat in.txt
foo
bar
baz
ham
spam
$ cat process.py
#!/usr/bin/env python
lines = open("in.txt").readlines()
lines.sort()
out = open("out.txt", "w")
for line in lines:
out.write(line)
out.close()
$ python process.py
$ cat out.txt
bar
baz
foo
ham
spam

Regards
G.
 
N

Novitiate

-Galahad,

Thank you very much. I will give it a shot and see if I can make it
hapen. I think this will help a lot.

I was just trying to implement a simple sorting algorithm that I knew
from C++, for practice but I couldn't figure the mechanics of Python.
Thanks again,

Novitiate
 
N

Novitiate

-Galahad,

Thank you very much. I will give it a shot and see if I can make it
hapen. I think this will help a lot.

I was just trying to implement a simple sorting algorithm that I knew
from C++, for practice but I couldn't figure the mechanics of Python.
Thanks again,

Novitiate
 
M

Mike Meyer

Sir Galahad the chaste said:
Hi,



What do you mean by "sorting"? If you want to sort the lines contained
in a file, you could do something like this.

$ cat in.txt
foo
bar
baz
ham
spam
$ cat process.py
#!/usr/bin/env python
lines = open("in.txt").readlines()

Some people consider it bad style to leave opened files lieing around,
so this shold be:

f = open("in.txt")
lines = f.readlines()
f.close()
lines.sort()
out = open("out.txt", "w")
for line in lines:
out.write(line)

Those two should be
out.writelines(lines)
out.close()

<mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top