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

How can saying a song's name be a copyright violation?

In a Spin are Both Wings Stalled?

Does casting Light, or a similar spell, have any effect when the caster is swallowed by a monster?

90's TV series where a boy goes to another dimension through portal near power lines

Why is Collection not simply treated as Collection<?>

Why do I get two different answers for this counting problem?

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

Where does SFDX store details about scratch orgs?

Fully-Firstable Anagram Sets

I Accidentally Deleted a Stock Terminal Theme

What's the difference between 'rename' and 'mv'?

Is "remove commented out code" correct English?

I'm flying to France today and my passport expires in less than 2 months

Python: return float 1.0 as int 1 but float 1.5 as float 1.5

Can I use a neutral wire from another outlet to repair a broken neutral?

How to take photos in burst mode, without vibration?

How do I write bicross product symbols in latex?

Theorems that impeded progress

1960's book about a plague that kills all white people

Has there ever been an airliner design involving reducing generator load by installing solar panels?

UK: Is there precedent for the governments e-petition site changing the direction of a government decision?

Did converts (ger tzedek) in ancient Israel own land?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Will google still index a page if I use a $_SESSION variable?



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






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








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
    Apr 1 at 14:28










  • $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
    Apr 1 at 14:56

















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
    Apr 1 at 14:28










  • $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
    Apr 1 at 14:56













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 Apr 1 at 16:48









200_success

131k17157422




131k17157422










asked Apr 1 at 13:23









Emily AldenEmily Alden

24228




24228











  • $begingroup$
    Can you edit your question to explain what the loop is supposed to do?
    $endgroup$
    – David White
    Apr 1 at 14:28










  • $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
    Apr 1 at 14:56
















  • $begingroup$
    Can you edit your question to explain what the loop is supposed to do?
    $endgroup$
    – David White
    Apr 1 at 14:28










  • $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
    Apr 1 at 14:56















$begingroup$
Can you edit your question to explain what the loop is supposed to do?
$endgroup$
– David White
Apr 1 at 14:28




$begingroup$
Can you edit your question to explain what the loop is supposed to do?
$endgroup$
– David White
Apr 1 at 14:28












$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
Apr 1 at 14:56




$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
Apr 1 at 14:56










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
    Apr 1 at 21:07


















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
    Apr 1 at 18:22










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    Apr 1 at 19:11










  • $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
    Apr 1 at 19:36







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    Apr 1 at 19:48










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    Apr 1 at 19:50











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
    Apr 1 at 21:07















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
    Apr 1 at 21:07













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 Apr 1 at 15:20









HoboProberHoboProber

4116




4116











  • $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
    Apr 1 at 21:07
















  • $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
    Apr 1 at 21:07















$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
Apr 1 at 21:07




$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
Apr 1 at 21:07













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
    Apr 1 at 18:22










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    Apr 1 at 19:11










  • $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
    Apr 1 at 19:36







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    Apr 1 at 19:48










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    Apr 1 at 19:50















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
    Apr 1 at 18:22










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    Apr 1 at 19:11










  • $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
    Apr 1 at 19:36







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    Apr 1 at 19:48










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    Apr 1 at 19:50













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 Apr 1 at 15:39









Benjamin KuykendallBenjamin Kuykendall

75329




75329











  • $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
    Apr 1 at 18:22










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    Apr 1 at 19:11










  • $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
    Apr 1 at 19:36







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    Apr 1 at 19:48










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    Apr 1 at 19:50
















  • $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
    Apr 1 at 18:22










  • $begingroup$
    @EmilyAlden Why accept an answer when you don’t understand why that answer works?
    $endgroup$
    – David White
    Apr 1 at 19:11










  • $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
    Apr 1 at 19:36







  • 1




    $begingroup$
    @EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
    $endgroup$
    – wizzwizz4
    Apr 1 at 19:48










  • $begingroup$
    @wizzwizz4 Thank you.
    $endgroup$
    – Emily Alden
    Apr 1 at 19:50















$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
Apr 1 at 18:22




$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
Apr 1 at 18:22












$begingroup$
@EmilyAlden Why accept an answer when you don’t understand why that answer works?
$endgroup$
– David White
Apr 1 at 19:11




$begingroup$
@EmilyAlden Why accept an answer when you don’t understand why that answer works?
$endgroup$
– David White
Apr 1 at 19:11












$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
Apr 1 at 19:36





$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
Apr 1 at 19:36





1




1




$begingroup$
@EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
$endgroup$
– wizzwizz4
Apr 1 at 19:48




$begingroup$
@EmilyAlden first_line = next(iterator) is equivalent to for first_line in iterator: break
$endgroup$
– wizzwizz4
Apr 1 at 19:48












$begingroup$
@wizzwizz4 Thank you.
$endgroup$
– Emily Alden
Apr 1 at 19:50




$begingroup$
@wizzwizz4 Thank you.
$endgroup$
– Emily Alden
Apr 1 at 19:50

















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

រឿង រ៉ូមេអូ និង ហ្ស៊ុយលីយេ សង្ខេបរឿង តួអង្គ បញ្ជីណែនាំ

Crop image to path created in TikZ? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Crop an inserted image?TikZ pictures does not appear in posterImage behind and beyond crop marks?Tikz picture as large as possible on A4 PageTransparency vs image compression dilemmaHow to crop background from image automatically?Image does not cropTikzexternal capturing crop marks when externalizing pgfplots?How to include image path that contains a dollar signCrop image with left size given

Romeo and Juliet ContentsCharactersSynopsisSourcesDate and textThemes and motifsCriticism and interpretationLegacyScene by sceneSee alsoNotes and referencesSourcesExternal linksNavigation menu"Consumer Price Index (estimate) 1800–"10.2307/28710160037-3222287101610.1093/res/II.5.31910.2307/45967845967810.2307/2869925286992510.1525/jams.1982.35.3.03a00050"Dada Masilo: South African dancer who breaks the rules"10.1093/res/os-XV.57.1610.2307/28680942868094"Sweet Sorrow: Mann-Korman's Romeo and Juliet Closes Sept. 5 at MN's Ordway"the original10.2307/45957745957710.1017/CCOL0521570476.009"Ram Leela box office collections hit massive Rs 100 crore, pulverises prediction"Archived"Broadway Revival of Romeo and Juliet, Starring Orlando Bloom and Condola Rashad, Will Close Dec. 8"Archived10.1075/jhp.7.1.04hon"Wherefore art thou, Romeo? To make us laugh at Navy Pier"the original10.1093/gmo/9781561592630.article.O006772"Ram-leela Review Roundup: Critics Hail Film as Best Adaptation of Romeo and Juliet"Archived10.2307/31946310047-77293194631"Romeo and Juliet get Twitter treatment""Juliet's Nurse by Lois Leveen""Romeo and Juliet: Orlando Bloom's Broadway Debut Released in Theaters for Valentine's Day"Archived"Romeo and Juliet Has No Balcony"10.1093/gmo/9781561592630.article.O00778110.2307/2867423286742310.1076/enst.82.2.115.959510.1080/00138380601042675"A plague o' both your houses: error in GCSE exam paper forces apology""Juliet of the Five O'Clock Shadow, and Other Wonders"10.2307/33912430027-4321339124310.2307/28487440038-7134284874410.2307/29123140149-661129123144728341M"Weekender Guide: Shakespeare on The Drive""balcony"UK public library membership"romeo"UK public library membership10.1017/CCOL9780521844291"Post-Zionist Critique on Israel and the Palestinians Part III: Popular Culture"10.2307/25379071533-86140377-919X2537907"Capulets and Montagues: UK exam board admit mixing names up in Romeo and Juliet paper"Istoria Novellamente Ritrovata di Due Nobili Amanti2027/mdp.390150822329610820-750X"GCSE exam error: Board accidentally rewrites Shakespeare"10.2307/29176390149-66112917639"Exam board apologises after error in English GCSE paper which confused characters in Shakespeare's Romeo and Juliet""From Mariotto and Ganozza to Romeo and Guilietta: Metamorphoses of a Renaissance Tale"10.2307/37323537323510.2307/2867455286745510.2307/28678912867891"10 Questions for Taylor Swift"10.2307/28680922868092"Haymarket Theatre""The Zeffirelli Way: Revealing Talk by Florentine Director""Michael Smuin: 1938-2007 / Prolific dance director had showy career"The Life and Art of Edwin BoothRomeo and JulietRomeo and JulietRomeo and JulietRomeo and JulietEasy Read Romeo and JulietRomeo and Julieteeecb12003684p(data)4099369-3n8211610759dbe00d-a9e2-41a3-b2c1-977dd692899302814385X313670221313670221