I'm trying to read fileA
and write the contents of fileA
to fileB
while having the line numbers right-justified in 4 columns, but I keep getting "none" output.
fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
lineNo = 0
f = open(fileA, 'r')
g = open(fileB, 'w')
for line in f:
lineNo = 1
h = print(lineNo,">", line)
j = str(h).rjust(4, " ")
g.write(str(j))
CodePudding user response:
There were a few bugs, but as pointed out, the print statement was causing the most problem. Here is a debugged version:
fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
lineNo = 0
f = open(fileA, 'r')
g = open(fileB, 'w')
for line in f:
lineNo = 1
h = str(lineNo).rjust(4) ">" line
g.write(h)
CodePudding user response:
print
can write to a file as well as the console with a file=g
parameter, but you'll find that print
also adds a newline while line
already has one in the string. Use end=''
to supress the extra line number.
enumerate
is a nice function for numbering what is being iterated over. It defaults numbering from zero, but adding start=1
will number from one.
Use with
statements to make sure your files are closed. Without closing the file, it might not be flushed to disk when running your code in some IDEs.
Example:
fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
with open(fileA, 'r') as f, open(fileB, 'w') as g:
for lineNo,line in enumerate(f, start=1):
print(f"{lineNo:>4}> {line}", end='', file=g)