smarter way of reading from a .txt file (for-loop?)











up vote
0
down vote

favorite












I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.



import os

parent_dir = "../dirfiles"
os.chdir(parent_dir)

file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"

read_file = open(file_name, read_mode)

the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))

the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))

the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))

read_file.close()


How the output should look like:



Initial of the first name is: Y
The last name is: Person
The age is: 18









share|improve this question




















  • 1




    If it only has one line, why would you need a loop?
    – Barmar
    Nov 7 at 20:34










  • why not csv module?
    – mad_
    Nov 7 at 20:35










  • @mad_: The input isn't comma-separated, or anything-separated at all.
    – user2357112
    Nov 7 at 20:35






  • 1




    Read the line and split it using regular expressions.
    – yorodm
    Nov 7 at 20:36










  • @user2357112 we can still specify which delimiter to use. Although I think a simple read would be enough in this case and (if there are multiple rows) loop through it
    – mad_
    Nov 7 at 20:58















up vote
0
down vote

favorite












I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.



import os

parent_dir = "../dirfiles"
os.chdir(parent_dir)

file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"

read_file = open(file_name, read_mode)

the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))

the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))

the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))

read_file.close()


How the output should look like:



Initial of the first name is: Y
The last name is: Person
The age is: 18









share|improve this question




















  • 1




    If it only has one line, why would you need a loop?
    – Barmar
    Nov 7 at 20:34










  • why not csv module?
    – mad_
    Nov 7 at 20:35










  • @mad_: The input isn't comma-separated, or anything-separated at all.
    – user2357112
    Nov 7 at 20:35






  • 1




    Read the line and split it using regular expressions.
    – yorodm
    Nov 7 at 20:36










  • @user2357112 we can still specify which delimiter to use. Although I think a simple read would be enough in this case and (if there are multiple rows) loop through it
    – mad_
    Nov 7 at 20:58













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.



import os

parent_dir = "../dirfiles"
os.chdir(parent_dir)

file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"

read_file = open(file_name, read_mode)

the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))

the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))

the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))

read_file.close()


How the output should look like:



Initial of the first name is: Y
The last name is: Person
The age is: 18









share|improve this question















I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.



import os

parent_dir = "../dirfiles"
os.chdir(parent_dir)

file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"

read_file = open(file_name, read_mode)

the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))

the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))

the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))

read_file.close()


How the output should look like:



Initial of the first name is: Y
The last name is: Person
The age is: 18






python file for-loop operating-system






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 20:36









Barmar

413k34238339




413k34238339










asked Nov 7 at 20:32









Mitchell Dehn

133




133








  • 1




    If it only has one line, why would you need a loop?
    – Barmar
    Nov 7 at 20:34










  • why not csv module?
    – mad_
    Nov 7 at 20:35










  • @mad_: The input isn't comma-separated, or anything-separated at all.
    – user2357112
    Nov 7 at 20:35






  • 1




    Read the line and split it using regular expressions.
    – yorodm
    Nov 7 at 20:36










  • @user2357112 we can still specify which delimiter to use. Although I think a simple read would be enough in this case and (if there are multiple rows) loop through it
    – mad_
    Nov 7 at 20:58














  • 1




    If it only has one line, why would you need a loop?
    – Barmar
    Nov 7 at 20:34










  • why not csv module?
    – mad_
    Nov 7 at 20:35










  • @mad_: The input isn't comma-separated, or anything-separated at all.
    – user2357112
    Nov 7 at 20:35






  • 1




    Read the line and split it using regular expressions.
    – yorodm
    Nov 7 at 20:36










  • @user2357112 we can still specify which delimiter to use. Although I think a simple read would be enough in this case and (if there are multiple rows) loop through it
    – mad_
    Nov 7 at 20:58








1




1




If it only has one line, why would you need a loop?
– Barmar
Nov 7 at 20:34




If it only has one line, why would you need a loop?
– Barmar
Nov 7 at 20:34












why not csv module?
– mad_
Nov 7 at 20:35




why not csv module?
– mad_
Nov 7 at 20:35












@mad_: The input isn't comma-separated, or anything-separated at all.
– user2357112
Nov 7 at 20:35




@mad_: The input isn't comma-separated, or anything-separated at all.
– user2357112
Nov 7 at 20:35




1




1




Read the line and split it using regular expressions.
– yorodm
Nov 7 at 20:36




Read the line and split it using regular expressions.
– yorodm
Nov 7 at 20:36












@user2357112 we can still specify which delimiter to use. Although I think a simple read would be enough in this case and (if there are multiple rows) loop through it
– mad_
Nov 7 at 20:58




@user2357112 we can still specify which delimiter to use. Although I think a simple read would be enough in this case and (if there are multiple rows) loop through it
– mad_
Nov 7 at 20:58












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










You could read the whole file into a string variable, then use slice notation to get parts of it.



with read_file = open(file_name, read_mode):
line = read_file.read().strip()
initial = line[0]
last_name = line[1:7]
age = int(line[7:])





share|improve this answer





















    Your Answer






    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: "1"
    };
    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',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    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%2fstackoverflow.com%2fquestions%2f53197376%2fsmarter-way-of-reading-from-a-txt-file-for-loop%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    You could read the whole file into a string variable, then use slice notation to get parts of it.



    with read_file = open(file_name, read_mode):
    line = read_file.read().strip()
    initial = line[0]
    last_name = line[1:7]
    age = int(line[7:])





    share|improve this answer

























      up vote
      0
      down vote



      accepted










      You could read the whole file into a string variable, then use slice notation to get parts of it.



      with read_file = open(file_name, read_mode):
      line = read_file.read().strip()
      initial = line[0]
      last_name = line[1:7]
      age = int(line[7:])





      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        You could read the whole file into a string variable, then use slice notation to get parts of it.



        with read_file = open(file_name, read_mode):
        line = read_file.read().strip()
        initial = line[0]
        last_name = line[1:7]
        age = int(line[7:])





        share|improve this answer












        You could read the whole file into a string variable, then use slice notation to get parts of it.



        with read_file = open(file_name, read_mode):
        line = read_file.read().strip()
        initial = line[0]
        last_name = line[1:7]
        age = int(line[7:])






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 7 at 20:37









        Barmar

        413k34238339




        413k34238339






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53197376%2fsmarter-way-of-reading-from-a-txt-file-for-loop%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