Read/write a pipe-delimited file line by line with some simple text manipulationRead file line-by-line with circular bufferRead Space Delimited Text File to Standardized Data Typefunction responsible for parsing 2 csv txt files, comparing them and writing csv txt files as outputC++ Read File line by lineA minimal CLI password storage and retrieval managerPython read/write pickled fileSimple python code takes command line argument for file location and tokenizes textRead integers from text file and write to CSV fileFile manipulation with HaskellRead and write BMP file in C

Can the Meissner effect explain very large floating structures?

What killed these X2 caps?

Should I cover my bicycle overnight while bikepacking?

Avoiding the "not like other girls" trope?

Plagiarism or not?

What about the virus in 12 Monkeys?

One verb to replace 'be a member of' a club

Unlock My Phone! February 2018

What is a romance in Latin?

Is it acceptable for a professor to tell male students to not think that they are smarter than female students?

Why no variance term in Bayesian logistic regression?

Short story with a alien planet, government officials must wear exploding medallions

Extract rows of a table, that include less than x NULLs

Why doesn't using multiple commands with a || or && conditional work?

How writing a dominant 7 sus4 chord in RNA ( Vsus7 chord in the 1st inversion)

Personal Teleportation: From Rags to Riches

Is it logically or scientifically possible to artificially send energy to the body?

Why didn't Boeing produce its own regional jet?

What is the most common color to indicate the input-field is disabled?

Is it possible to create a QR code using text?

How do I gain back my faith in my PhD degree?

GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?

Arrow those variables!

Am I breaking OOP practice with this architecture?



Read/write a pipe-delimited file line by line with some simple text manipulation


Read file line-by-line with circular bufferRead Space Delimited Text File to Standardized Data Typefunction responsible for parsing 2 csv txt files, comparing them and writing csv txt files as outputC++ Read File line by lineA minimal CLI password storage and retrieval managerPython read/write pickled fileSimple python code takes command line argument for file location and tokenizes textRead integers from text file and write to CSV fileFile manipulation with HaskellRead and write BMP file in C













9












$begingroup$


This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion.



I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.



counter=1
for line in open(r"C:Pathname.txt"):
spline = line.split("|")
if counter==1:
with open(r"C:PATH2019.txt",'a') as NewFile:
spline.insert(23,"Column A")
spline.insert(23,"Column B")
s="|"
newline=s.join(spline)
NewFile.write(newline)

elif counter > 1 and not spline[22]=="0.00":
spline.insert(23,"")
spline.insert(23,"")
gl=spline[0]
gl=gl.strip()
if gl[0]=="-": gl="000" + gl
gl=gl.upper()
spline[0]=gl

if gl[:3]=="000": spline[24]="Incorrect"

s="|"
newline=s.join(spline)

with open(r"C:PATHPythonWrittenData.txt",'a') as NewFile:
NewFile.write(newline)

counter+=1
if counter%100000==0: print("Status Update: n", ":,".format(counter))









share|improve this question











$endgroup$











  • $begingroup$
    Can you edit your question to explain what the loop is supposed to do?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line.
    $endgroup$
    – Emily Alden
    2 days ago















9












$begingroup$


This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion.



I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.



counter=1
for line in open(r"C:Pathname.txt"):
spline = line.split("|")
if counter==1:
with open(r"C:PATH2019.txt",'a') as NewFile:
spline.insert(23,"Column A")
spline.insert(23,"Column B")
s="|"
newline=s.join(spline)
NewFile.write(newline)

elif counter > 1 and not spline[22]=="0.00":
spline.insert(23,"")
spline.insert(23,"")
gl=spline[0]
gl=gl.strip()
if gl[0]=="-": gl="000" + gl
gl=gl.upper()
spline[0]=gl

if gl[:3]=="000": spline[24]="Incorrect"

s="|"
newline=s.join(spline)

with open(r"C:PATHPythonWrittenData.txt",'a') as NewFile:
NewFile.write(newline)

counter+=1
if counter%100000==0: print("Status Update: n", ":,".format(counter))









share|improve this question











$endgroup$











  • $begingroup$
    Can you edit your question to explain what the loop is supposed to do?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line.
    $endgroup$
    – Emily Alden
    2 days ago













9












9








9





$begingroup$


This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion.



I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.



counter=1
for line in open(r"C:Pathname.txt"):
spline = line.split("|")
if counter==1:
with open(r"C:PATH2019.txt",'a') as NewFile:
spline.insert(23,"Column A")
spline.insert(23,"Column B")
s="|"
newline=s.join(spline)
NewFile.write(newline)

elif counter > 1 and not spline[22]=="0.00":
spline.insert(23,"")
spline.insert(23,"")
gl=spline[0]
gl=gl.strip()
if gl[0]=="-": gl="000" + gl
gl=gl.upper()
spline[0]=gl

if gl[:3]=="000": spline[24]="Incorrect"

s="|"
newline=s.join(spline)

with open(r"C:PATHPythonWrittenData.txt",'a') as NewFile:
NewFile.write(newline)

counter+=1
if counter%100000==0: print("Status Update: n", ":,".format(counter))









share|improve this question











$endgroup$




This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion.



I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.



counter=1
for line in open(r"C:Pathname.txt"):
spline = line.split("|")
if counter==1:
with open(r"C:PATH2019.txt",'a') as NewFile:
spline.insert(23,"Column A")
spline.insert(23,"Column B")
s="|"
newline=s.join(spline)
NewFile.write(newline)

elif counter > 1 and not spline[22]=="0.00":
spline.insert(23,"")
spline.insert(23,"")
gl=spline[0]
gl=gl.strip()
if gl[0]=="-": gl="000" + gl
gl=gl.upper()
spline[0]=gl

if gl[:3]=="000": spline[24]="Incorrect"

s="|"
newline=s.join(spline)

with open(r"C:PATHPythonWrittenData.txt",'a') as NewFile:
NewFile.write(newline)

counter+=1
if counter%100000==0: print("Status Update: n", ":,".format(counter))






python beginner python-3.x file csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









200_success

131k17157422




131k17157422










asked 2 days ago









Emily AldenEmily Alden

24228




24228











  • $begingroup$
    Can you edit your question to explain what the loop is supposed to do?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line.
    $endgroup$
    – Emily Alden
    2 days ago
















  • $begingroup$
    Can you edit your question to explain what the loop is supposed to do?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line.
    $endgroup$
    – Emily Alden
    2 days ago















$begingroup$
Can you edit your question to explain what the loop is supposed to do?
$endgroup$
– David White
2 days ago




$begingroup$
Can you edit your question to explain what the loop is supposed to do?
$endgroup$
– David White
2 days ago












$begingroup$
@DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line.
$endgroup$
– Emily Alden
2 days ago




$begingroup$
@DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line.
$endgroup$
– Emily Alden
2 days ago










2 Answers
2






active

oldest

votes


















6












$begingroup$

A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:



with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:
for line in file_one:
...
for line in file_two:
...


This is a very common way of reading from one file and writing to another without continually opening and closing one of them.



Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in name.txt, checks an if / elif condition, then if either are satisfied, a file is opened, written to, then closed again with every iteration of the loop.



Simply by opening both files at the same time you can stop opening and closing them repeatedly.



For more info on the with statement and other context managers, see here.




Another small improvement can be made. At the moment, you check the first if condition every time, but you know it will only actually evaluate to True once. it would be better to remove that check and just always perform that block once. Assign counter after the first block (after where if counter == 1 currently is) then replace the elif statement with a while loop.




It would be worth getting familiar with PEP8 if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.




If you include an example file and desired output, there may be more I can help with.






share|improve this answer









$endgroup$












  • $begingroup$
    I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
    $endgroup$
    – Emily Alden
    2 days ago


















8












$begingroup$

Here is another way to organize your code. Instead of an if within the loop, use iterators more explicitly. Concretely:



with open(r"C:Pathname.txt") as source:
lines = iter(source)

# first line
first_line = next(lines)
with open(r"C:PATH2019.txt") as summary:
# ... omitted ...

# remaining lines
with open(r"C:PATHPythonWrittenData.txt", 'a') as dest:
for counter, line in enumerate(lines, start=1):
# ... omitted ...



I have also used enumerate to update counter and line simultaneously.



The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.






share|improve this answer









$endgroup$












  • $begingroup$
    I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
    $endgroup$
    – Emily Alden
    2 days ago










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
    $endgroup$
    – Emily Alden
    2 days ago







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    2 days ago










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    2 days ago











Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216653%2fread-write-a-pipe-delimited-file-line-by-line-with-some-simple-text-manipulation%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









6












$begingroup$

A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:



with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:
for line in file_one:
...
for line in file_two:
...


This is a very common way of reading from one file and writing to another without continually opening and closing one of them.



Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in name.txt, checks an if / elif condition, then if either are satisfied, a file is opened, written to, then closed again with every iteration of the loop.



Simply by opening both files at the same time you can stop opening and closing them repeatedly.



For more info on the with statement and other context managers, see here.




Another small improvement can be made. At the moment, you check the first if condition every time, but you know it will only actually evaluate to True once. it would be better to remove that check and just always perform that block once. Assign counter after the first block (after where if counter == 1 currently is) then replace the elif statement with a while loop.




It would be worth getting familiar with PEP8 if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.




If you include an example file and desired output, there may be more I can help with.






share|improve this answer









$endgroup$












  • $begingroup$
    I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
    $endgroup$
    – Emily Alden
    2 days ago















6












$begingroup$

A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:



with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:
for line in file_one:
...
for line in file_two:
...


This is a very common way of reading from one file and writing to another without continually opening and closing one of them.



Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in name.txt, checks an if / elif condition, then if either are satisfied, a file is opened, written to, then closed again with every iteration of the loop.



Simply by opening both files at the same time you can stop opening and closing them repeatedly.



For more info on the with statement and other context managers, see here.




Another small improvement can be made. At the moment, you check the first if condition every time, but you know it will only actually evaluate to True once. it would be better to remove that check and just always perform that block once. Assign counter after the first block (after where if counter == 1 currently is) then replace the elif statement with a while loop.




It would be worth getting familiar with PEP8 if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.




If you include an example file and desired output, there may be more I can help with.






share|improve this answer









$endgroup$












  • $begingroup$
    I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
    $endgroup$
    – Emily Alden
    2 days ago













6












6








6





$begingroup$

A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:



with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:
for line in file_one:
...
for line in file_two:
...


This is a very common way of reading from one file and writing to another without continually opening and closing one of them.



Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in name.txt, checks an if / elif condition, then if either are satisfied, a file is opened, written to, then closed again with every iteration of the loop.



Simply by opening both files at the same time you can stop opening and closing them repeatedly.



For more info on the with statement and other context managers, see here.




Another small improvement can be made. At the moment, you check the first if condition every time, but you know it will only actually evaluate to True once. it would be better to remove that check and just always perform that block once. Assign counter after the first block (after where if counter == 1 currently is) then replace the elif statement with a while loop.




It would be worth getting familiar with PEP8 if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.




If you include an example file and desired output, there may be more I can help with.






share|improve this answer









$endgroup$



A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:



with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:
for line in file_one:
...
for line in file_two:
...


This is a very common way of reading from one file and writing to another without continually opening and closing one of them.



Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in name.txt, checks an if / elif condition, then if either are satisfied, a file is opened, written to, then closed again with every iteration of the loop.



Simply by opening both files at the same time you can stop opening and closing them repeatedly.



For more info on the with statement and other context managers, see here.




Another small improvement can be made. At the moment, you check the first if condition every time, but you know it will only actually evaluate to True once. it would be better to remove that check and just always perform that block once. Assign counter after the first block (after where if counter == 1 currently is) then replace the elif statement with a while loop.




It would be worth getting familiar with PEP8 if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.




If you include an example file and desired output, there may be more I can help with.







share|improve this answer












share|improve this answer



share|improve this answer










answered 2 days ago









HoboProberHoboProber

4066




4066











  • $begingroup$
    I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
    $endgroup$
    – Emily Alden
    2 days ago
















  • $begingroup$
    I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
    $endgroup$
    – Emily Alden
    2 days ago















$begingroup$
I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
$endgroup$
– Emily Alden
2 days ago




$begingroup$
I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant.
$endgroup$
– Emily Alden
2 days ago













8












$begingroup$

Here is another way to organize your code. Instead of an if within the loop, use iterators more explicitly. Concretely:



with open(r"C:Pathname.txt") as source:
lines = iter(source)

# first line
first_line = next(lines)
with open(r"C:PATH2019.txt") as summary:
# ... omitted ...

# remaining lines
with open(r"C:PATHPythonWrittenData.txt", 'a') as dest:
for counter, line in enumerate(lines, start=1):
# ... omitted ...



I have also used enumerate to update counter and line simultaneously.



The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.






share|improve this answer









$endgroup$












  • $begingroup$
    I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
    $endgroup$
    – Emily Alden
    2 days ago










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
    $endgroup$
    – Emily Alden
    2 days ago







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    2 days ago










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    2 days ago















8












$begingroup$

Here is another way to organize your code. Instead of an if within the loop, use iterators more explicitly. Concretely:



with open(r"C:Pathname.txt") as source:
lines = iter(source)

# first line
first_line = next(lines)
with open(r"C:PATH2019.txt") as summary:
# ... omitted ...

# remaining lines
with open(r"C:PATHPythonWrittenData.txt", 'a') as dest:
for counter, line in enumerate(lines, start=1):
# ... omitted ...



I have also used enumerate to update counter and line simultaneously.



The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.






share|improve this answer









$endgroup$












  • $begingroup$
    I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
    $endgroup$
    – Emily Alden
    2 days ago










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
    $endgroup$
    – Emily Alden
    2 days ago







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    2 days ago










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    2 days ago













8












8








8





$begingroup$

Here is another way to organize your code. Instead of an if within the loop, use iterators more explicitly. Concretely:



with open(r"C:Pathname.txt") as source:
lines = iter(source)

# first line
first_line = next(lines)
with open(r"C:PATH2019.txt") as summary:
# ... omitted ...

# remaining lines
with open(r"C:PATHPythonWrittenData.txt", 'a') as dest:
for counter, line in enumerate(lines, start=1):
# ... omitted ...



I have also used enumerate to update counter and line simultaneously.



The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.






share|improve this answer









$endgroup$



Here is another way to organize your code. Instead of an if within the loop, use iterators more explicitly. Concretely:



with open(r"C:Pathname.txt") as source:
lines = iter(source)

# first line
first_line = next(lines)
with open(r"C:PATH2019.txt") as summary:
# ... omitted ...

# remaining lines
with open(r"C:PATHPythonWrittenData.txt", 'a') as dest:
for counter, line in enumerate(lines, start=1):
# ... omitted ...



I have also used enumerate to update counter and line simultaneously.



The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.







share|improve this answer












share|improve this answer



share|improve this answer










answered 2 days ago









Benjamin KuykendallBenjamin Kuykendall

72829




72829











  • $begingroup$
    I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
    $endgroup$
    – Emily Alden
    2 days ago










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
    $endgroup$
    – Emily Alden
    2 days ago







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    2 days ago










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    2 days ago
















  • $begingroup$
    I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
    $endgroup$
    – Emily Alden
    2 days ago










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    2 days ago










  • $begingroup$
    @DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
    $endgroup$
    – Emily Alden
    2 days ago







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    2 days ago










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    2 days ago















$begingroup$
I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
$endgroup$
– Emily Alden
2 days ago




$begingroup$
I'm not sure I understand the reasoning behind first_line=next(lines) could you explain how it should be used?
$endgroup$
– Emily Alden
2 days ago












$begingroup$
@EmilyAlden Why accept an answer when you don’t understand why that answer works?
$endgroup$
– David White
2 days ago




$begingroup$
@EmilyAlden Why accept an answer when you don’t understand why that answer works?
$endgroup$
– David White
2 days ago












$begingroup$
@DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
$endgroup$
– Emily Alden
2 days ago





$begingroup$
@DavidWhite: Honestly I bounced between which answer to accept. I understand the use of iter and enumerate here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though).
$endgroup$
– Emily Alden
2 days ago





1




1




$begingroup$
@EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
$endgroup$
– wizzwizz4
2 days ago




$begingroup$
@EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
$endgroup$
– wizzwizz4
2 days ago












$begingroup$
@wizzwizz4 Thank you.
$endgroup$
– Emily Alden
2 days ago




$begingroup$
@wizzwizz4 Thank you.
$endgroup$
– Emily Alden
2 days ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216653%2fread-write-a-pipe-delimited-file-line-by-line-with-some-simple-text-manipulation%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020