views:

56

answers:

2

hello guys can anyone led me what i should do with cut from file

so how i can told my python open items.txt then cut 20 lines from beginning then paste it on Sold-items.txt

+1  A: 

Small files solution.

fr = open('items.txt', 'w')
fw = open('Sold-items.txt', 'w')
f = fr.readlines()
fr.write('\n'.join(f[20:]))
fr.close()    
fw.write('\n'.join(f[:20]))
fw.close()
Ashish
Ashish nice work but your code copy not cut !! thanks alot for trying
Joey
@Joey: now cut.
Ashish
A: 

Read up on readlines and writelines.

with open('Sold-items.txt', 'w') as f:
    f.writelines(open('items.txt').readlines()[20:])

Please note that you may want to think about a slightly different solution for large files.


And after reading comments it appears that your question really wants this:

"Remove the first 20 lines from file A and put them into file B."

file_A = "items.txt"
file_B = "Sold-items.txt"

lines = open(file_A).readlines()
with open(file_A, 'w') as a, open(file_B, 'w') as b:
    b.writelines(lines[:20]) # first 20 lines
    a.writelines(lines[20:]) # the rest of the lines 

Please edit the question for clarity as two out of three answers read it the same way and none of three answers understood the 'cut' part actually meant modify the original file until given more information.

istruble
Note that this doesn't remove the first 20 lines from items.txt.
JoshD
@JoshD: It does, doesn't it? It reads all the lines into memory and then writes out only those from 20 on. See `[20:]`?
hughdbrown
@hughdbrown: Maybe I misunderstand the code. Ashish has an answer that does what I expect. From what I see on istruble's answer, sold items gets lines beyond 20; items.txt isn't changed. Is that right, or am I reading it wrong?
JoshD
Correct @JoshD, this only reads lines from items.txt (nothing removed) but it also writes any lines after the first 20 to Sold-items.txt. Check out slice notation: http://docs.python.org/library/stdtypes.html?highlight=slice%20notation#sequence-types-str-unicode-list-tuple-buffer-xrange
istruble
@istruble: OK. That's exactly what I thought it did, but that's not what the OP wants. Sold-items.txt should have the first 20 lines. items.txt should have all lines beyond 20. See Ashish's answer.
JoshD
@JoshD: uh, yeah. You are right. ANd that means my solution is wrong...
hughdbrown
anyway thanks guys for helping
Joey