Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Slicing to a file
#11
And removing the for loops in this case just displays the outfile with no text. Really stumped to what I am missing

import sys
print(" *** Truncating File Copy ***")
infile_name = input("Please enter the name of the file to copy: ")
outfile_name = input("Please enter the name of the new copy:  ")
infile = open(infile_name, 'r+', errors = 'ignore')
outfile = open(outfile_name, 'w+')
newList = infile.readlines()
def omit():
       omitline = int(input("Omit how many lines from the start:"))
       newList[omitline:]
def omit2():
       omitline2 = int(input("Omit how many lines from the end:"))
       newList[:omitline2]
omit()
omit2()
outfile.write(infile.read())
infile.close()
outfile.close()
Reply
#12
For one thing, I told you that you didn't need the for loops, and you didn't get rid of them. The one for trimming the end won't be a problem, but if you repeatedly trim from the beginning then you will end up with no string. The way your program is, if I want to trim three characters from the beginning, it will trim three characters three times, so it will trim nine characters.

Second, slicing a list (as in newList[:omitLine]) returns a new list that is a trimmed version of the old list. In your two functions you don't do anything with that new list. You would generally assign the new list to something, in this case maybe the name of the old list. However, you are doing this inside a function. I'm pretty sure we've talked about this before, but you want to be passing parameters to your functions and returning values from them. So I would say pass newList as a parameter to omit, and return the sliced newList from omit, so that you end up with this line:

newList = omit(newList)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020