使用Python编辑CSVFiles

2024-07-03 05:44:39 发布

您现在位置:Python中文网/ 问答频道 /正文

一般来说,我对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

Tags: csvruninpymainlibasline
1条回答
网友
1楼 · 发布于 2024-07-03 05:44:39

您混合了两种不同的读取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("\\", "/")

相关问题 更多 >