Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

python - How to remove a single line of data from one csv and write it to a different csv?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are few issues in your code:

  1. park and chosen_park are local variables inside new_park(), so they cannot be accessed inside confirm_park(). They need to be declared global inside new_park().

  2. You should read the park list outside new_park() and just randomly choose a park inside the function.

  3. you are not saving the chosen_park to stl_parks_visited.csv.

  4. park is a list of park names with trailing " " in each park name. Use park = f.read().splitlines() to remove the trailing " ".

According to your code, it seems like that stl_park_list.csv contains the park name only in each line. So using pandas to convert the list park to dataframe and save the dataframe to file is not necessary. Just use simple file operation to append chosen_park to output file is enough.

Below are modified new_park() and confirm_park():

with open("stl_parks_list.csv") as f:
    park = f.read().splitlines()

def new_park():
    global chosen_park
    chosen_park = random.choice(park)
    canvas.itemconfig(park_text, text=chosen_park)  


def confirm_park():
    park.remove(chosen_park)
    print(len(park))
    with open("data/stl_parks_visited.csv", "a") as f:
        print(chosen_park, file=f)

With the above change, the GET PARK button is not necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...