{"id":5590,"date":"2025-05-11T12:06:29","date_gmt":"2025-05-11T04:06:29","guid":{"rendered":"http:\/\/192.168.1.29\/?p=5590"},"modified":"2025-05-11T14:05:05","modified_gmt":"2025-05-11T06:05:05","slug":"python%e8%8e%b7%e5%8f%96a%e6%95%85%e6%95%b0%e6%8d%ae%e5%b9%b6%e5%ad%98%e5%85%a5csv%e6%96%87%e4%bb%b6","status":"publish","type":"post","link":"http:\/\/cnliutz.wicp.vip\/?p=5590","title":{"rendered":"python\u83b7\u53d6A\u80a1\u6570\u636e\u5e76\u5b58\u5165csv\u6587\u4ef6"},"content":{"rendered":"\n<pre class=\"wp-block-code\"><code>import akshare as ak\nimport pandas as pd\nimport os\nimport schedule\nimport time\nimport logging\n\ndef get_and_save_stock_data():\n        \"\"\"\n        Fetches the latest A-share stock data from Eastmoney and saves it to an Excel file.\n        The file is named with a timestamp and stored in the same directory as the script.\n        Logs the success or failure of the operation.\n        \"\"\"\n        try:\n            # \u83b7\u53d6\u80a1\u7968\u6570\u636e\n            # data = ak.stock_zh_a_spot_em()\n            data = ak.stock_zh_a_spot()\n            print(data.head(150))\n            # \u6253\u5370\u6570\u636e\u7684\u57fa\u672c\u4fe1\u606f\n            print(\"\u6570\u636e\u57fa\u672c\u4fe1\u606f\uff1a\")\n            data.info()\n            # \u6253\u5370\u6570\u636e\u884c\u6570\u548c\u5217\u6570\n            rows, columns = data.shape\n            if rows &lt; 3000:\n                print(\"\u6570\u636e\u53ef\u80fd\u672a\u83b7\u53d6\u5b8c\u6574\uff0c\u8bf7\u68c0\u67e5\u7f51\u7edc\u8fde\u63a5\u6216\u7a0d\u540e\u91cd\u8bd5\u3002\")\n            else:\n                print(\"\u6570\u636e\u83b7\u53d6\u5b8c\u6574\u3002\")\n            # \u6253\u5370\u6570\u636e\u884c\u6570\n            print(\"\u6570\u636e\u884c\u6570\uff1a\", rows)\n\n            # \u751f\u6210\u5e26\u65f6\u95f4\u7684\u6587\u4ef6\u540d\n            current_time = time.strftime(\"%Y%m%d%H%M%S\")\n            # Generate a file name with a timestamp\n            file_name = f'stock_data_{current_time}.xlsx'\n            # Create a full file path by combining the directory of the current script and the file name\n            file_path = os.path.join(os.path.dirname(__file__), file_name)\n            # Write the data to an Excel file, without including the index\n            data.to_excel(file_path, index=False)\n            # Log the successful retrieval and storage of the stock data\n            logging.info(f\"Successfully retrieved stock data and saved to {file_path} at {time.strftime('%Y-%m-%d %H:%M:%S')}\")\n        except Exception as e:\n            # Log any errors that occur during the retrieval or storage of the stock data\n            logging.error(f\"An error occurred while retrieving or saving stock data: {e}\")\n\n# Configure logging to record events at the INFO level\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n# Schedule the function to run every 1 minute\nschedule.every(0.5).minutes.do(get_and_save_stock_data)\n\n# Start the scheduling loop\ntry:\n    import msvcrt  # Import msvcrt module for Windows key detection\n    import keyboard  # Import the keyboard library\n    logging.info(\"Press 'Q' or 'q' to terminate the program.\")\n\n    while True:\n        schedule.run_pending()\n        time.sleep(.5)\n        \n        # Check if the 'Q' key is pressed\n        if msvcrt.kbhit() and msvcrt.getch().decode('utf-8').upper() == 'Q':\n            logging.info(\"Program terminated by user.\")\n            break\n        # Check if the 'q' key is pressed\n        if keyboard.is_pressed('q'):\n            logging.info(\"Program terminated by user.\")\n            break\nexcept KeyboardInterrupt:\n    logging.info(\"Program terminated by user.\u7ed3\u675f\")\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,10],"tags":[],"class_list":["post-5590","post","type-post","status-publish","format-standard","hentry","category-2","category-python"],"_links":{"self":[{"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=\/wp\/v2\/posts\/5590","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5590"}],"version-history":[{"count":2,"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=\/wp\/v2\/posts\/5590\/revisions"}],"predecessor-version":[{"id":5592,"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=\/wp\/v2\/posts\/5590\/revisions\/5592"}],"wp:attachment":[{"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5590"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5590"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/cnliutz.wicp.vip\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5590"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}