【问题标题】:Edit CSV-Files with Python使用 Python 编辑 CSV 文件
【发布时间】:2021-09-28 01:42:03
【问题描述】:

我对 Python 和一般编程非常陌生,所以请简单解释一下。 我试图更改一个 CSV 文件,但我总是收到错误,我该如何解决?

代码:

import pandas as pd

with pd.read_csv ('D: \ P \ Python projects \ correct CSV \ test.csv') as file

if "\\" in file:
betterfile = file.replace ("\\", "/")
print (betterfile)```

Error:
Traceback (most recent call last):
File "C: \ Users \ Vinstand YT \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ runpy.py", line 197, in _run_module_as_main
return _run_code (code, main_globals, None,
File "C: \ Users \ Vinstand YT \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ runpy.py", line 87, in _run_code
exec (code, run_globals)
File "c: \ Users \ Vinstand YT \ .vscode \ extensions \ ms-python.python-2021.6.944021595 \ pythonFiles \ lib \ python \ debugpy \ __ main__.py", line 45, in <module>
cli.main ()
File "c: \ Users \ Vinstand YT \ .vscode \ extensions \ ms-python.python-2021.6.944021595 \ pythonFiles \ lib \ python \ debugpy / .. \ debugpy \ server \ cli.py", line 444, in main
run()
File "c: \ Users \ Vinstand YT \ .vscode \ extensions \ ms-python.python-2021.6.944021595 \ pythonFiles \ lib \ python \ debugpy / .. \ debugpy \ server \ cli.py", line 285, in run_file
runpy.run_path (target_as_str, run_name = compat.force_str ("__ main__"))
File "C: \ Users \ Vinstand YT \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ runpy.py", line 267, in run_path
code, fname = _get_code_from_file (run_name, path_name)
File "C: \ Users \ Vinstand YT \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ runpy.py", line 242, in _get_code_from_file
code = compile (f.read (), fname, 'exec')
File "d: \ P \ Python Projects \ Correct CSV \ Project CSV corrector.py", line 3
with pd.read_csv ('D: \ P \ Python Projects \ Correct CSV \ test.csv') as file
^
SyntaxError: invalid syntax

【问题讨论】:

  • “import Pandas as pd”在代码中缺失
  • 您不能使用pd.read_csvwithpd.read_csv 返回一个数据框,而 with 为您提供文件的上下文管理视图。查看10 minutes to pandas 教程,特别是“获取数据输入/输出”部分。

标签: python pandas csv


【解决方案1】:

您混淆了两种不同的读取 csv 文件的方式。

  1. pd.read_csv
  2. open

pd.read_csv用于读取文件到pandas.DataFrame

为了你的目的,你可以坚持使用open

with open('D:\P\Python projects\correct CSV \test.csv') as file:
    contents = file.read()
if "\\" in contents:
    betterfile = file.replace("\\", "/")

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 2014-01-15
    • 2012-12-24
    • 2018-04-22
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多